0

I have a simple Checkbox

<div>
   <input type="checkbox" id="chkBox1" value="Test" /> Test
</div>

MVC 5 renders this html for this checkbox

<div class="checker" id="uniform-chkBox1">
   <span class="checked">
     <input type="checkbox" value="Test" id="chkBox1">
   </span>
</div>

I want to uncheck this checkbox using Javascript/JQuery but I cannot figure it out. Using Firebug, when I remove the span class "checked" the checkbox gets unchecked but I cannot figure out how to do this in Javascript.

5
  • 1
    Show the jQuery you are trying to use to uncheck the box. Commented Oct 16, 2014 at 19:19
  • 1
    'but I cannot figure it out' - What did you try? Commented Oct 16, 2014 at 19:19
  • stackoverflow.com/questions/426258/… Commented Oct 16, 2014 at 19:21
  • Checking/unchecking checkboxes with JavaScript has to be the #1 all time most asked dupe. Commented Oct 16, 2014 at 19:22
  • This sounds like an issue with your selector. How are you selecting your checkbox? Commented Oct 16, 2014 at 19:31

2 Answers 2

1

$('#chkBox1').prop('checked', true)

checks it off and

$('#chkBox1').prop('checked', false) turns if off.

Instead of prop(), you can also use attr()

If you instead want to just remove the class checked from the span element. you can do

$('#uniform-chkBox1 span.checked').removeClass('checked')

Sign up to request clarification or add additional context in comments.

3 Comments

Your answer is very close, only removing the checked class from span gets it unchecked but now to check it again, it requires 2 clicks. It just doesn't gets checked on first click :(
Perhaps there's some strange JavaScript is generates to handle this. Why don't you try both doing $('#chkBox1').prop('checked', false) and $('#uniform-chkBox1 span.checked').removeClass('checked') ?
Thank You very much, First I removed the span class and then set the .prop to false and it is working like a charm now.
1

Use .prop().

In your case $("#chkBox1").prop("checked", false); will uncheck and $("#chkBox1").prop("checked", true); will check.

Run code below to see in action.

setInterval(function() {
  if ($("#chkBox1").prop("checked"))
    $("#chkBox1").prop("checked", false);
  else
    $("#chkBox1").prop("checked", true);
  }, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" value="Test" id="chkBox1" 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.