Smeegs
Smeegs

Reputation: 9224

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");
});

Upvotes: 4

Views: 9810

Answers (4)

oded
oded

Reputation: 121

you can use this:

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

Upvotes: 1

Dhaval Marthak
Dhaval Marthak

Reputation: 17366

Use .prop()

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

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

Fiddle Demo

Upvotes: 2

Satpal
Satpal

Reputation: 133453

Use .prop()

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

DEMO

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

Upvotes: 2

A. Wolff
A. Wolff

Reputation: 74420

Use .prop() to set property checked instead:

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

Upvotes: 11

Related Questions