[英]Return an array with jquery .val()
I have a set of checkboxes and want to concatenate only the checked ones into a query string, but for some reason val() only returns the first one. 我有一组复选框,只想将选中的复选框连接到查询字符串中,但是由于某种原因,val()仅返回第一个复选框。 The jQuery API docs mention that selects can return an array form the .val() function, can I get this same behavior for inputs as well, with a prototype or jquery plugin?
jQuery API文档提到selects可以从.val()函数返回一个数组,我是否也可以使用原型或jquery插件获得相同的输入行为?
Here's my code: 这是我的代码:
$('.boxes input:checked');
// [ <input type="checkbox" value="val1">, <input type="checkbox" value="val2">, <input type="checkbox" value="val3"> ]
$('.boxes input:checked').val();
// "val1"
Ideally the second console output would be: 理想情况下,第二个控制台输出为:
$('.boxes input:checked').val();
// [ "val1", "val2", "val3" ]
val
returns an array of selected values for select
elements that have multiple
attribute, for other elements it returns the value of the first element in the set. val
返回具有multiple
属性的select
元素的选定值的数组,对于其他元素,它返回集合中第一个元素的值。 You can use the map
method: 您可以使用
map
方法:
var values = $('.boxes input:checked').map(function() {
return this.value;
}).get();
You can also define a method: 您还可以定义一个方法:
$.fn.vals = function() {
var first = this.get(0);
if ( this.length === 0 ) return [];
if ( first.tagName === 'SELECT' && first.multiple ) {
return this.val();
}
return this.map(function() { return this.value; }).get();
}
// ...
var values = $('.boxes input:checked').vals();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.