5

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.

2
  • Wrap your attribute selectors in quotes. $('input:checkbox[name="check[]"]').val(); Commented Dec 6, 2011 at 21:39
  • 1
    Thanks guys - I learnt a lot here. I don't like the 'answer tick' thing, but gave it TJC, because he got in a minute earlier... :) I do like the jsFiddle thing, though. Commented Dec 6, 2011 at 22:12

3 Answers 3

7

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:

var vals = []
$('input:checkbox[name="check[]"]').each(function() {
    vals.push(this.value);
});

Or if you only want the checked ones:

var vals = []
$('input:checkbox[name="check[]"]').each(function() {
    if (this.checked) {
        vals.push(this.value);
    }
});

Or you can use map and get:

var vals = $('input:checkbox[name="check[]"]').map(function() {
    return this.value;
}).get();

Or if you only want the checked ones:

var vals = $('input:checkbox[name="check[]"]').map(function() {
    return this.checked ? this.value : undefined;
}).get();

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.value in the iterator functions above to get the value of the input, rather than $(this).val(). It's pretty much just a style thing, neither is better than the other from all perspectives. this.value is 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 other input elements, it isn't reliable cross-browser with some other form fields (select boxes, for instance). $(this).val() is more idiomatic in a jQuery-intensive application, and you don't have to worry about whether this is an input or a select. Yes, it adds overhead, but if you don't have thousands of them, it's not like it's going to matter.

Sign up to request clarification or add additional context in comments.

2 Comments

You don't need to escape the square braces if you put your attribute selector in strings, like you're supposed to: $('input:checkbox[name="check[]"]').val();.
@Rocket: Thanks. Curiously, I was just thinking "Hey, wait, I forgot that jQuery wants quotes" (it's a jQuery thing, not a CSS thing).
4
  • If you are not familiar with the .map() method, let me introduce one of my favorites. The example on the manual page also features checkboxes. The .get() method can be used to transform a jQuery collection into an object.

.map(): Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.

  • Other knowledge you need is that you have escape [] with backslashes inside the attribute selector: name=check\[\]]. Edit: Of course if you use the standard attribute selector syntax, there will be no problem: name="check[]"

Something like this would suffice:

var checkedValues = $('input:checkbox[name="check[]"]:checked').map(function () {
    return $(this).val();
}).get();

jsFiddle Demo

2 Comments

You don't need to escape the square braces if you put your attribute selector in strings, like you're supposed to: $('input:checkbox[name="check[]"]').val();.
@Rocket Thanks, seen your comment under TJ's answer and already started to correct mine.
0

I would think serialize() and serializeArray() array would work, but apparently they apply only to children of the selection.

Worst case I would just use map() to get the array like so

country : $("your input selector").map(function() {return $(this).val();})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.