1

background

I have a table grid of checkboxes, grouped by name, and each checkbox contains a time value. An example of the HTML:

<td><input type="checkbox" name="tuesday[]" value="10am"></td>
<td><input type="checkbox" name="tuesday[]" value="11am"></td>
<td><input type="checkbox" name="tuesday[]" value="12pm"></td>
<td><input type="checkbox" name="tuesday[]" value="1pm"></td>
<td><input type="checkbox" name="tuesday[]" value="2pm"></td>
<td><input type="checkbox" name="tuesday[]" value="3pm"></td>
<td><input type="checkbox" name="tuesday[]" value="4pm"></td>
<td><input type="checkbox" name="tuesday[]" value="5pm"></td>
<td><input type="checkbox" name="tuesday[]" value="6pm"></td>
<td><input type="checkbox" name="tuesday[]" value="7pm"></td>

When the form is submitted, the values are POSTed how I want them to be; all the checked times are in the tuesday[] array.

problem

I want to do some client-side validation with jQuery. I want to check that at least one checkbox is checked.

I have tried storing it into a var like so:

var availTuesday  = $("input:checkbox[name='tuesday']:checked");

But when I do so and the console.log(availTuesday);, nothing is shown (regardless on if something is checked or not). I have also tried console.log(availTuesday.serialize());

Question:

how can I retrieve the user-checked values for the tuesday[] checkbox group, as well as for the other dates (wednesday[], thursday[], etc)?

Thank you.

2
  • 1
    you name in the selector doesn't match the name of the checkbox. Commented Jan 2, 2014 at 21:56
  • jQuery doesn't parse the [] outside of $.param(). The brackets should be included in the selector. [name='tuesday[]']. Commented Jan 2, 2014 at 21:57

5 Answers 5

5

The selector is not correct, change it to:

var $tuesday = $("input[type=checkbox][name='tuesday[]']:checked");

For getting the values you can use .map() method which returns an array:

if ($tuesday.length) {
   // Getting values of the checked checkboxes
   var values = $tuesday.map(function(){
        return this.value;
   }).get();
   // ...
} else {
    // There is no checked `day[]` checkbox
}

In case that you have other similar set of checkboxes you can use an array:

var days = ['days', 'in', 'a', 'week'],
    values = {},
    errors = [],
    $checkboxes = $("input[type=checkbox]");

$.each(days, function(_, day) {
  var $set = $checkboxes.filter('[name="'+day+'[]"]:checked');
  if ($set.length) {
      values[day] = $set.map(function() {
          return this.value;
      }).get();
  } else {
      // There is no checked `day[]` checkbox
      errors.push(day);
  }
});

if (errors.length) {
   // console.log('Please check at least one hour in ' + errors.join(', ') + ' days ...');
} else {
  // console.log(values);
}
Sign up to request clarification or add additional context in comments.

1 Comment

lot of great answers here so it was hard to pick a best, but I think I learned the most from your post, so thank you. :)
1

You can try

var availTuesday = [];
    $('input[type=checkbox][name="tuesday[]"]:checked').each(function() {
       availTuesday.push($(this).val()); 
    });

JSFiddle

Comments

0

If you want the actual value

var values = $("input[type=checkbox][name='tuesday[]']:checked").map(function() {
    return this.value;
}).get();

Comments

0

If all you are really after is if any boxes are selected you can do the following:

if($('input[type="checkbox"][name="tuesday[]"]:checked').length) {
    ...
} else {
    ...
}

The length value is a property of the jQuery object (superset of DOM object) that specifies how many nodes matched the selector. In this case, if you check the length and the value is 0, no :checked checkboxes with the name tuesday[] exist (i.e. the user has not checked any boxes so display your validation message). It's quick and dirty validation. If you're looking to retrieve the values, the multitude of other answers are probably better.

Comments

0

You'll need to fix the selector to match the name, as others have mentioned.
If you just want to test that one is checked, you can go straight to a boolean, like this:

var availTuesday  = $("input:checkbox[name='tuesday[]']:checked").length > 0;

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.