jQuery 如何使用jquery获取输入类型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3165413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:57:21  来源:igfitidea点击:

How to get input type using jquery?

jqueryinputtypes

提问by Luci

I have a page where the input type always varies, and I need to get the values depending on the input type. So if the type is a radio, I need to get which is checked, and if it is a checkbox I need to now which are checked, and if it is a drop down I need to know which is selected, and I if it is a text/textarea I need to know the values.

我有一个页面,其中输入类型总是不同,我需要根据输入类型获取值。所以如果类型是收音机,我需要检查哪个被选中,如果它是一个复选框,我现在需要选中哪个,如果它是一个下拉列表,我需要知道哪个被选中,如果它是一个 text/textarea 我需要知道这些值。

Any idea on how to do that?

关于如何做到这一点的任何想法?

回答by Mark Schultheiss

EDIT Feb 1, 2013. Due to the popularity of this answer and the changes to jQuery in version 1.9 (and 2.0) regarding properties and attributes, I added some notes and a fiddle to see how it works when accessing properties/attributes on input, buttons and some selects. The fiddle here: http://jsfiddle.net/pVBU8/1/

编辑 2013 年 2 月 1 日。由于此答案的流行以及 1.9(和 2.0)版 jQuery 中关于属性和属性的更改,我添加了一些注释和小提琴,以了解在访问输入的属性/属性时它是如何工作的,按钮和一些选择。这里的小提琴:http: //jsfiddle.net/pVBU8/1/



get all the inputs:

获取所有输入:

var allInputs = $(":input");

get all the inputs type:

获取所有输入类型:

allInputs.attr('type');

get the values:

获取值:

allInputs.val();

NOTE: .val() is NOT the same as :checked for those types where that is relevent. use:

注意: .val() 与 :checked 对于那些相关的类型不同。用:

.attr("checked");


EDIT Feb 1, 2013 - re: jQuery 1.9 use prop() not attr() as attr will not return proper values for properties that have changed.

编辑 2013 年 2 月 1 日 - 回复:jQuery 1.9 使用 prop() 而不是 attr() 因为 attr 不会为已更改的属性返回正确的值。

.prop('checked');

or simply

或者干脆

$(this).checked;


to get the value of the check - whatever it is currently. or simply use the ':checked' if you want only those that ARE checked.

获取支票的价值 - 无论当前是什么。或者如果你只想要那些被检查的,就简单地使用 ':checked'。

EDIT: Here is another way to get type:

编辑:这是获取类型的另一种方法:

var allCheckboxes=$('[type=checkbox]');

EDIT2: Note that the form of:

EDIT2:请注意以下形式:

$('input:radio');

is perferred over

优于

$(':radio');

which both equate to:

这两者都等同于:

$('input[type=radio]');

but the "input" is desired so it only gets the inputs and does not use the universal '*" when the form of $(':radio')is used which equates to $('*:radio');

但是“输入”是需要的,所以它只获取输入而不使用通用的“*”,当使用的形式$(':radio')等于$('*:radio');

EDIT Aug 19, 2015: preference for the $('input[type=radio]');should be used as that then allows modern browsers to optimize the search for a radio input.

编辑 2015 年 8 月 19 日:首选$('input[type=radio]');应使用,因为这样可以让现代浏览器优化对无线电输入的搜索。



EDIT Feb 1, 2013 per comment re: select elements @dariomac

编辑 2013 年 2 月 1 日每条评论:选择元素 @dariomac

$('select').prop("type");

will return either "select-one" or "select-multiple" depending upon the "multiple" attribute and

将根据“multiple”属性返回“select-one”或“select-multiple”

$('select')[0].type 

returns the same for the first select if it exists. and

如果存在,则为第一个选择返回相同的值。和

($('select')[0]?$('select')[0].type:"howdy") 

will return the type if it exists or "howdy" if it does not.

如果存在则返回类型,如果不存在则返回“howdy”。

 $('select').prop('type');

returns the property of the first one in the DOM if it exists or "undefined" if none exist.

如果存在则返回 DOM 中第一个的属性,如果不存在则返回“未定义”。

$('select').type

returns the type of the first one if it exists or an error if none exist.

如果存在则返回第一个的类型,如果不存在则返回错误。

回答by xil3

You could do the following:

您可以执行以下操作:

var inputType = $('#inputid').attr('type');

回答by user113716

If what you're saying is that you want to get all inputs inside a form that have a value without worrying about the input type, try this:

如果您想在不担心输入类型的情况下获取具有值的表单中的所有输入,请尝试以下操作:

Example:http://jsfiddle.net/nfLfa/

示例:http : //jsfiddle.net/nfLfa/

var $inputs = $('form').find(':checked,:selected,:text,textarea').filter(function() {
    return $.trim( this.value ) != '';
});

Now you should have a set of input elements that have some value.

现在您应该有一组具有某些值的输入元素。

You can put the values in an array:

您可以将值放入数组中:

var array = $inputs.map(function(){
    return this.value;
}).get();

Or you could serialize them:

或者你可以序列化它们:

var serialized = $inputs.serialize();

回答by Matthew Abbott

GetValue = function(id) {
  var tag = this.tagName;
  var type = this.attr("type");

  if (tag == "input" && (type == "checkbox" || type == "radio"))
    return this.is(":checked");

  return this.val();
};

回答by Robert

The best place to start looking is http://api.jquery.com/category/selectors/

开始寻找的最佳地点是 http://api.jquery.com/category/selectors/

This will give you a good set of examples.

这将为您提供一组很好的示例。

Ultamatly the selecting of elements in the DOM is achived using CSS selectors so if you think about getting an element by id you will want to use $('#elementId'), if you want all the input tags use $('input') and finaly the part i think you'll want if you want all input tags with a type of checkbox use $('input, [type=checkbox])

最终,DOM 中元素的选择是使用 CSS 选择器实现的,因此如果您考虑通过 id 获取元素,您将需要使用 $('#elementId'),如果您希望所有输入标签都使用 $('input')最后,如果您希望所有带有复选框类型的输入标签使用 $('input, [type=checkbox])

Note: You'll find most of the values you want are on attributes so the css selector for attributes is: [attributeName=value]

注意:你会发现你想要的大部分值都在属性上,所以属性的 css 选择器是:[attributeName=value]

Just because you asked for the dropdown as aposed to a listbox try the following:

仅仅因为您要求下拉列表框的下拉列表,请尝试以下操作:


$('select, [size]).each(function(){
  var selectedItem = $('select, [select]', this).first();
});

The code was from memory so please accound for small errors

该代码来自内存,所以请注意小错误

回答by Ergec

$("#yourobj").attr('type');

回答by pat capozzi

It would seem that the attr functionality is getting further deprecated

似乎 attr 功能正在进一步被弃用

$(this).attr('TYPE')
undefined
$(this).prop('type')
"text"

回答by Boldewyn

var val = $('input:checkbox:checked, input:radio:checked, \
   select option:selected, textarea, input:text',
   $('#container')).val();

Comments:

注释:

  1. I assume, that there is exactly oneform element, that can be either a textarea, input field, select form, a set of radio buttons or a single checkbox (you will have to update my code if you need more checkboxes).

  2. The element in question lives inside an element with ID container(to remove ambiguences with other elements on the page).

  3. The code will then return the value of the firstmatching element it finds. Since I use :checkedand so on, this should always be exactly the value of what you're looking for.

  1. 我假设只有一个表单元素,可以是文本区域、输入字段、选择表单、一组单选按钮或单个复选框(如果需要更多复选框,则必须更新我的代码)。

  2. 有问题的元素位于具有 ID 的元素内container(以消除与页面上其他元素的歧义)。

  3. 然后代码将返回它找到的第一个匹配元素的值。由于我使用:checked等等,这应该始终是您正在寻找的价值。

回答by Tibi

In my application I ended up with two different elements having the same id (bad). One element was a div and the other an input. I was trying to sum up my inputs and took me a while to realise the duplicate ids. By placing the type of the element I wanted in front of #, I was able to grab the value of the input element and discard the div:

在我的应用程序中,我最终得到了两个具有相同 ID(坏)的不同元素。一个元素是一个 div,另一个是输入。我试图总结我的输入并花了我一段时间来意识到重复的 ID。通过将我想要的元素类型放在 # 前面,我能够获取输入元素的值并丢弃 div:

$("input#_myelementid").val();

I hope it helps.

我希望它有帮助。

回答by Amit Dwivedi

<!DOCTYPE html>
<html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
          $(".show-pwd").click(function(){
          alert();
            var x = $("#myInput");
            if (x[0].type === "password") {
              x[0].type = "text";
            } else {
              x[0].type = "password";
            }
          });
        });
    </script>
</head>

<body>
    <p>Click the radio button to toggle between password visibility:</p>Password:
    <input type="password" value="FakePSW" id="myInput">
    <br>
    <br>
    <input type="checkbox" class="show-pwd">Show Password</body>

</html>