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.
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" />
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');
$(checkbox).prop("checked"). Also you don't need to check if is true. You can sum it up tocheckbox.checked ? checbox.checked = false : checkbox.checked = truecheckbox.checked = !checkbox.checked;