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.

Adil Khalil
  • 2,073
  • 3
  • 21
  • 33

2 Answers2

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 />
Dave
  • 10,748
  • 3
  • 43
  • 54
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')

taveras
  • 485
  • 3
  • 12
  • 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 :( – Adil Khalil Oct 16 '14 at 19:39
  • 1
    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')` ? – taveras Oct 16 '14 at 19:43
  • 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. – Adil Khalil Oct 16 '14 at 19:54