Destiny In Ur Hands
Destiny In Ur Hands

Reputation: 199

Check or uncheck all checkboxes with same classname based on value

I've the following checkboxes in multiple divs.

<div class="div1">
    <input type="checkbox" class="chkbox" value="101"> This is 101
    <input type="checkbox" class="chkbox" value="102"> This is 102
    <input type="checkbox" class="chkbox" value="103"> This is 103
</div>
<div class="div2">
    <input type="checkbox" class="chkbox" value="110"> This is 110
    <input type="checkbox" class="chkbox" value="102"> This is 102
    <input type="checkbox" class="chkbox" value="101"> This is 101
</div>

As shown above, some of the checkboxes have the same value (e.g., 101) across multiple divs. Now, whenever a checkbox is checked, I need to check other checkboxes with the same value. Similarly, for uncheck.

$(".chkbox").change(function() {
    // If checked
    if (this.checked)
           // find other checkboxes with same value and check them
    else
           // find other checkboxes with same value and uncheck them
}

Upvotes: 7

Views: 18855

Answers (5)

Adil
Adil

Reputation: 148120

You can do it like this.

Live Demo

$(".chkbox").change(function() {
    // If checked
    if (this.checked)
           $(":checkbox[value=" + this.value + "]").attr('checked', true);
    else
           $(":checkbox[value=" + this.value + "]").attr('checked', false);           // find other checkboxes with same value and uncheck them
})

You missed the closing paraenthesis ) of change event.

Upvotes: 0

Vinod Joshi
Vinod Joshi

Reputation: 7862

// if user has already sent the survey
    if(user_id_value){

        var result = confirm("This user already received a survey. Are you sure you want to resend?");

        // do not send the survey again
        if(!result){            
            $(":checkbox[value='"+user_id+"']").attr("checked", false);         
        }// end if not confirmed

    }// end if 

Upvotes: 0

dherman
dherman

Reputation: 2892

$( ".chkbox" ).change(function() {
  var value = $( this ).attr( "value" );

  $( ".chkbox[value='" + value + "']" ).prop( "checked", this.checked );
});

Upvotes: 0

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

you could do:

$(".chkbox").change(function() {
    var val = $(this).val();
  if( $(this).is(":checked") ) {

    $(":checkbox[value='"+val+"']").attr("checked", true);
  }
    else {
        $(":checkbox[value='"+val+"']").attr("checked", false);
    }
});

Demo: jsFiddle

Upvotes: 11

Barmar
Barmar

Reputation: 780994

$(".chkbox").change(function() {
    $(":checkbox[value="+$(this).val()+"]").prop("checked", this.checked);
}

Upvotes: 3

Related Questions