admin管理员组

文章数量:1403355

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.

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.

Share Improve this question asked Jan 2, 2014 at 21:54 tdctdc 5,46412 gold badges59 silver badges107 bronze badges 2
  • 1 you name in the selector doesn't match the name of the checkbox. – dandavis 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[]']. – Jonathan Lonowski Commented Jan 2, 2014 at 21:57
Add a ment  | 

5 Answers 5

Reset to default 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);
}

You can try

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

JSFiddle

If you want the actual value

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

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.

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;

本文标签: javascriptjQuery store selected checkboxes into arrayStack Overflow