Return an array with jquery .val()

2019-06-10 13:43发布

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" ]

1条回答
等我变得足够好
2楼-- · 2019-06-10 13:56

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();
查看更多
登录 后发表回答