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
  • 711
  • 1
  • 9
  • 19

4 Answers4

1
var $checkbox = $(/*your selector*/);
$checkbox.prop("checked", !$checkbox.prop("checked" ) );
Sebastian Osuna
  • 367
  • 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
  • 22,994
  • 11
  • 59
  • 91
0
$(document).ready(function() {
    $("#YourIdSelector,.YourClassSelector").click(function() {
        $(this).prop('checked',!$(this).is(':checked'));
    });                 
});

Hope it helps...

Mayank
  • 1,291
  • 5
  • 21
  • 38
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
  • 26,843
  • 4
  • 58
  • 80