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
  • 687
  • 6
  • 19
cj333
  • 2,467
  • 20
  • 65
  • 107

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
  • 68,720
  • 11
  • 89
  • 123
2

You could do

if($('#select input:checked').val()=='2'){
    $('#select input').attr('checked','checked');
}
Nicola Peluchetti
  • 74,514
  • 30
  • 136
  • 188
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
  • 78,145
  • 14
  • 119
  • 133
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,868
  • 2
  • 42
  • 72