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");
});
Use .prop()
to set property checked instead:
$(".check").click(function () {
$(".LineCheckbox").prop("checked", true);
});
$(".uncheck").click(function () {
$(".LineCheckbox").prop("checked", false);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With