Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can't set an MVC checkbox as checked in jquery

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");
});
like image 361
Smeegs Avatar asked Dec 04 '22 08:12

Smeegs


1 Answers

Use .prop() to set property checked instead:

$(".check").click(function () {        
    $(".LineCheckbox").prop("checked", true);
});
$(".uncheck").click(function () {        
    $(".LineCheckbox").prop("checked", false);
});
like image 109
A. Wolff Avatar answered Dec 18 '22 21:12

A. Wolff