2

I want to make a judge, if checkbox value = 2, selected. But now my judge not work.

Jquery part

if($('#select input').attr('value')=='2'){
    $('#select input').attr('checked','checked');
}

Html part

<div id="select">
<input type="checkbox" name="my_check[]" value="1">item1</input>
<input type="checkbox" name="my_check[]" value="2">item2</input>
<input type="checkbox" name="my_check[]" value="3">item3</input>
<input type="checkbox" name="my_check[]" value="4">item4</input>
<input type="checkbox" name="my_check[]" value="5">item5</input>
</div>
Brad Fox
  • 685
  • 6
  • 19
cj333
  • 2,547
  • 20
  • 67
  • 110

4 Answers4

6

If you want to find out if checkbox with value 2 is checked then try this.

if($('#select input[value="2"]').prop('checked')){
      //
}

Since checked is a property of checkbox element it is recommended to use prop instead of attr.

ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
2

You could do

if($('#select input:checked').val()=='2'){
    $('#select input').attr('checked','checked');
}
Nicola Peluchetti
  • 76,206
  • 31
  • 145
  • 192
2

You can use .is and :checked to see if the checkbox is selected. Something like below should do the trick,

if ($('#select input[value=2]').is(':checked')) {
 //do what if checked.
}
Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134
0
$("#select input").change(function() {
    var value = $(this).prop("checked") ? 'true' : 'false';                     

    if(value == true) {
        alert('Checked');
    } else {
        alert('NOT Checked');
    }
});

See How to check whether a checkbox is checked in jQuery?

Community
  • 1
  • 1
Gabriel Santos
  • 4,934
  • 2
  • 43
  • 74