JsonStatham
JsonStatham

Reputation: 10364

MVC bool EditorFor value always true in JQUERY

I have the following bool on my form:

<div class="form-group">
    @Html.LabelFor(model => model.IsMonday, "Monday", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.IsMonday)
        @Html.ValidationMessageFor(model => model.IsMonday)
    </div>
</div>

Which renders as this:

<div class="form-group">
            <label class="control-label col-md-2" for="IsMonday">Monday</label>
            <div class="col-md-10">
                <input class="check-box" data-val="true" data-val-required="The IsMonday field is required." id="IsMonday" name="IsMonday" type="checkbox" value="true" />
                <input name="IsMonday" type="hidden" value="false" />
                <span class="field-validation-valid" data-valmsg-for="IsMonday" data-valmsg-replace="true"></span>
            </div>
        </div>

Regardless of whether I check the box, in Chrome Dev tools the following results in true:

$('#IsMonday').val()

Why is this happening, and how can I find out whether the box is checked or not i.e. true or false, not just true.

This question is not helping me in case anyone recommends it:

MVC 4 EditorFor bool Checkbox always posting True

Upvotes: 1

Views: 3607

Answers (2)

user3559349
user3559349

Reputation:

The reason it always returns true is because @Html.CheckBoxFor() renders 2 inputs

<input type="checkbox" name="IsMonday" .. value="true" >
<input type="hidden" name="IsMonday" .. value="false" >

which is used for binding (unchecked checkboxes do not post back so the hidden input ensures a value of false is posted). To check its state, you can use

$('#IsMonday').is(':checked')

Upvotes: 3

JsonStatham
JsonStatham

Reputation: 10364

Literally the minute I posted this I found the solution, as of JQUERY 1.6 the attr() method returns undefined which was another thing I had tried, this works:

$('#IsMonday').prop('checked')

Maybe it will help someone else.

Upvotes: 3

Related Questions