[jquery] check / uncheck checkbox using jquery?

I have some input text fields in my page and am displaying their values using JavaScript.

I am using .set("value","") function to edit the value, add an extra checkbox field, and to pass a value.

Here I want to check that if value == 1, then this checkbox should be checked. Otherwise, it should remain unchecked.

I did this by using two divs, but I am not feeling comfortable with that, is there any other solution?

if(value == 1) {
    $('#uncheck').hide();
    $('#check').show();
} else{
    $('#uncheck').show();
    $('#check').hide();
}

This question is related to jquery jquery-ui

The answer is


You can use prop() for this, as Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

var prop=false;
if(value == 1) {
   prop=true; 
}
$('#checkbox').prop('checked',prop);

or simply,

$('#checkbox').prop('checked',(value == 1));

Snippet

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  var chkbox = $('.customcheckbox');_x000D_
  $(".customvalue").keyup(function() {_x000D_
    chkbox.prop('checked', this.value==1);_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<h4>This is a domo to show check box is checked_x000D_
if you enter value 1 else check box will be unchecked </h4>_x000D_
Enter a value:_x000D_
<input type="text" value="" class="customvalue">_x000D_
<br>checkbox output :_x000D_
<input type="checkbox" class="customcheckbox">
_x000D_
_x000D_
_x000D_


You can set the state of the checkbox based on the value:

$('#your-checkbox').prop('checked', value == 1);