Reputation: 11377
I have an HTML form with a number of checkboxes that all have the same class="myClass"
.
How I can get the first, second and third value out of these? There can only be three checkboxes checked at a time but it can also be only two, one or none.
I tried the following but this doesn't work:
var check1 = 'myDefaultValue';
var check2 = 'myDefaultValue';
var check3 = 'myDefaultValue';
var checkedBoxes = $('.myClass:checked');
if(checkedBoxes.length == 1) {
check1 = checkedBoxes[0].val();
}
if(checkedBoxes.length == 2) {
check2 = checkedBoxes[1].val();
}
if(checkedBoxes.length == 3) {
check3 = checkedBoxes[2].val();
}
Upvotes: 0
Views: 1207
Reputation: 708
If you want the 3 first checked input fields you could do it with :eq() in the jquery selector like this:
// Get the first three values of all checked fields
var first = $('.myClass:checked:eq(0)').val();
var second = $('.myClass:checked:eq(1)').val();
var third = $('.myClass:checked:eq(2)').val();
see it in action here: http://jsfiddle.net/y0mwy5v8/
Upvotes: 1