This has got me stumped. I can easily get the value of a multiselect as an array, and pass it to an ajax request:
<select id="countries" class="multiselect" multiple="multiple" name="countries[]">
<option value="AFG">Afghanistan</option>
<etc>
...
$countries_input = $("#countries");
var countries = $countries_input.val();
$.ajax({
data: {
country : countries,
...
},
...
});
but I can’t find any equivalent way to get the values of a checkbox with multiple selections. The obvious stuff doesn’t work:
<input type="checkbox" name="check[]" value="foo1"/>foo1<br/>
<input type="checkbox" name="check[]" value="foo2"/>foo2<br/>
...
var bar = $('input:checkbox[name=check]').val(); // undefined
var bar = $('input:checkbox[name=check[]]').val(); // also undefined
var bar = $('input:checkbox[name=check]:checked').val(); // also undefined
Any ideas? Thanks.
There’s no built-in jQuery function for that. You have to do it yourself. You can do it easily enough with a simple loop:
Or if you only want the checked ones:
Or you can use
mapandget:Or if you only want the checked ones:
Side note 1: jQuery requires the value in an attribute value selector (the kind above) always be in quotes, although as of this writing despite documenting that it’s still lax about it. It’s a jQuery thing, but in this case you’d need it for CSS as well (CSS2 Reference | CSS3 Reference) because your value includes
[], which aren’t valid for values without quotes in CSS. (In CSS, without quotes the values must be identifiers.)Side note 2: Note I used
this.valuein the iterator functions above to get the value of theinput, rather than$(this).val(). It’s pretty much just a style thing, neither is better than the other from all perspectives.this.valueis more direct and if you know the DOM at all (and every web programmer should), it’s perfectly clear. But of course, while perfectly reliable cross-browser with checkboxes and most otherinputelements, it isn’t reliable cross-browser with some other form fields (selectboxes, for instance).$(this).val()is more idiomatic in a jQuery-intensive application, and you don’t have to worry about whetherthisis aninputor aselect. Yes, it adds overhead, but if you don’t have thousands of them, it’s not like it’s going to matter.