1

Since I am new to Jquery, I want a code in JQUERY for following function:

if(checkbox.checked==true)
{
checkbox.checked=false;
}
else
checkbox.checked=true;

please help me with this.

Manoj Kumar
  • 811
  • 2
  • 10
  • 22

4 Answers4

1
var $checkbox = $(/*your selector*/);
$checkbox.prop("checked", !$checkbox.prop("checked" ) );
Sebastian Osuna
  • 377
  • 2
  • 7
0

You can use following code: (Using .attr() or .prop())

var checkbox = $('#targetId');
if(checkbox.prop('checked')==true)
checkbox.prop('checked','false');
else
checkbox.prop('checked','true');

OR

var checkbox = $('#targetId');
if(checkbox.attr('checked')=='checked')
checkbox.attr('checked','checked');
else
checkbox.removeAttr('checked');
Manwal
  • 23,450
  • 12
  • 63
  • 93
0
$(document).ready(function() {
    $("#YourIdSelector,.YourClassSelector").click(function() {
        $(this).prop('checked',!$(this).is(':checked'));
    });                 
});

Hope it helps...

Mayank
  • 1,351
  • 5
  • 23
  • 42
0

See this snippet:

$("#btn").on("click", function() {
    $("input[type=checkbox]").each(function() {
        this.checked = !this.checked;
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" checked />
<input type="checkbox"  />
<input type="checkbox" checked />
<input type="checkbox"  />
<br /><br />
<input id="btn" type="button" value="Invert" />
Abhitalks
  • 27,721
  • 5
  • 58
  • 81