4

In MVC, I'm using helpers to create a checkbox like so

@Html.CheckBox("MDCCheckbox", true, new { @class = "LineCheckbox" })
@Html.Label("MDCCheckbox", "MDC")  

Nothing fancy.

I want to be able to (un)check the box in jquery.

I can uncheck it very easily, but I can't set it to checked. It's something with the way MVC renders the html, but I can't figure it out.

I know that I can just create the elements myself, but I want to know what I'm doing wrong.

This is how that razor is rendered into html (with a matching input element to pass true/false to the server).

<input checked="checked" class="LineCheckbox" id="MDCCheckbox" name="MDCCheckbox" type="checkbox" value="true" />
<input name="MDCCheckbox" type="hidden" value="false" />
<label for="MDCCheckbox">MDC</label> 

I've created a fiddle to make it easier to play with and test. I can't even get it to work in the fiddle.

fiddle

Here is the jquery

$(".check").click(function () {        
    $(".LineCheckbox").attr("checked", true);
});
$(".uncheck").click(function () {        
    $(".LineCheckbox").removeAttr("checked");
});
Smeegs
  • 9,151
  • 5
  • 42
  • 78

4 Answers4

11

Use .prop() to set property checked instead:

$(".check").click(function () {        
    $(".LineCheckbox").prop("checked", true);
});
$(".uncheck").click(function () {        
    $(".LineCheckbox").prop("checked", false);
});
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
2

Use .prop()

$(".check").click(function () {        
    $(".LineCheckbox").prop("checked", true);
});
$(".uncheck").click(function () {        
    $(".LineCheckbox").prop("checked", false);
});

DEMO

A good read .prop() vs .attr()

Community
  • 1
  • 1
Satpal
  • 132,252
  • 13
  • 159
  • 168
2

Use .prop()

$(".check").click(function () {        
    $(".LineCheckbox").prop("checked", true);
});

You can see the difference between .prop() and .attr()

Fiddle Demo

Community
  • 1
  • 1
Dhaval Marthak
  • 17,246
  • 6
  • 46
  • 68
1

you can use this:

$(".check").click(function () {        
    $('.LineCheckbox').prop('checked', true);
});
$(".uncheck").click(function () {        
     $('.LineCheckbox').prop('checked', false);
});
Satpal
  • 132,252
  • 13
  • 159
  • 168
oded
  • 121
  • 2