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.

5
  • 1
    $(checkbox).prop("checked"). Also you don't need to check if is true. You can sum it up to checkbox.checked ? checbox.checked = false : checkbox.checked = true Commented Nov 17, 2014 at 8:29
  • if I used this code previously:$(checkbox).removeAttr("checked") Then, is it possible to use this? $(checkbox).prop("checked") Commented Nov 17, 2014 at 8:31
  • 1
    possible duplicate of Toggle Checkboxes on/off Commented Nov 17, 2014 at 8:32
  • 3
    checkbox.checked = !checkbox.checked; Commented Nov 17, 2014 at 8:33
  • Np, also check @Vohuman comment. Is the best way. Commented Nov 17, 2014 at 8:35

4 Answers 4

1
var $checkbox = $(/*your selector*/);
$checkbox.prop("checked", !$checkbox.prop("checked" ) );
Sign up to request clarification or add additional context in comments.

Comments

0
$(document).ready(function() {
    $("#YourIdSelector,.YourClassSelector").click(function() {
        $(this).prop('checked',!$(this).is(':checked'));
    });                 
});

Hope it helps...

Comments

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" />

Comments

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');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.