用jquery .val()返回数组 [英] Return an array with jquery .val()
问题描述
我有一组复选框,并且只想将连接的查询串连接到查询字符串中,但由于某种原因,val()仅返回第一个。 jQuery API文档提到select可以从.val()函数返回一个数组,我可以通过原型或jquery插件获得相同的输入行为吗?
<这是我的代码:
$('。boxes input:checked');
// [< input type =checkboxvalue =val1> ;,< input type =checkboxvalue =val2>,< input type =checkboxvalue = VAL3\" > ]
$('。boxes input:checked')。val();
//val1
理想情况下,第二个控制台输出为:
$('。boxes input:checked')。val();
// [val1,val2,val3]
select
返回一个选定值的数组,该元素具有多个
属性,对于其他元素,它返回集合中第一个元素的值。您可以使用 map
方法: var values = $(' .boxes input:checked')。map(function(){
return this.value;
))。get();
您也可以定义一个方法:
$。fn.vals = function(){
var first = this.get(0);
if(this.length === 0)return [];
if(first.tagName ==='SELECT'&& first.multiple){
return this.val();
}
返回this.map(function(){return this.value;})。get();
}
// ...
var values = $('。boxes input:checked')。vals();
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. 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?
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. You can use the map
method:
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();
这篇关于用jquery .val()返回数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!