jQuery Checkbox selects other checkboxes with similar prefix
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

On a form, I have a list of hours in the day for each day of the week, each with a checkbox allowing someone to reserve that particular hour. See a static example: http://www.undr.com/dev/ws/

I'd like to have a header checkbox (in the day listing) that will choose all the hours of the day.

The checkboxes are currently coded like so: <input type="checkbox" name="dates" value="201303240900" />, where the value is encoded YYYYMMDDHHMM

The header checkbox should be able to select all the other checkboxes with the prefix YYYMMDD, which should limit it's selection to the same day.

Unchecking the box will also deselect the rest of the day as well.

In case you wanted to read more about attribute selectors, MDN is a great resource https://developer.mozilla.org/en-US/docs/CSS/Attribute_selectors
sguha 6 years ago
awarded to vmas

Crowdsource coding tasks.

3 Solutions

$(document).ready(function () {
    $('input[name="day"]').click(function () {
        if ($(this).prop('checked')) {
            $('input[value*="' + $(this).val() + '"]').prop('checked', true);
        } else {
           $('input[value*="' + $(this).val() + '"]').prop('checked', false);


Good job, however, I prefer the other two solutions use of change(), and the ^= vs. *= selectors.
underdesign 6 years ago
Winning solution

$('input[name=day]').change(function () {
       $('input[name=dates][value^=' + this.value + ']').removeAttr('checked').click();
       $('input[name=dates][value^=' + this.value + ']').removeAttr('checked').change();


$('th input').change(function () {
  var day = this.value;
  $('input[name=dates][value ^= ' + day + ']').prop('checked', this.checked);
I think it's better to use change() rather than clicked() so that it works even if the user uses the spacebar to check the checkbox
sguha 6 years ago
View Timeline