Reputation: 327
I have the following code
@foreach (var item in Model.Defaults)
{
<tr class="CertainCategory">
<td>
@item.Item1
</td>
<td>
@Html.CheckBoxFor(c => c.Use)
@Html.Hidden("guid", guid.guid.ToString())
</td>
</tr>
}
I'm trying to use AJAX to submit form values to the controller method. My problem is that the value of the checkbox is always sent as true
.
$('.CropUsageItem').each(function () {
var guid = $(this).find("#guid").val();
var chk = $(this).find("#use").val();
var data = {
guid: guid,
chk: chk
};
$.ajax({
async: false,
type: "POST",
url: "DefaultValues/SaveDefault",
data: data
});
});
I have searched StackOverflow with similar results but none of them fully apply to my scenario. How can I send the correct value?
Upvotes: 25
Views: 18319
Reputation: 13302
Like Simon said, .val() returns the value attribute of the checkbox, which can be any value you want. But more specifically, it returns the value property of the DOM object, which is initialized by the attribute. MVC seems to set the value to "true" by default, which seems pretty meaningless to me. But in some cases you might want want to set it to an ID or some other meaningful value for the checked option as this thread points out.
Nicholas provided one good way of getting whether the checkbox is checked above. Check and uncheck the checkbox on this jsfiddle for an example of the various approaches and their results:
Summary of fiddle:
$("#use").val(); //Returns the value. Not related to checked state.
$("#use").attr("checked") //Returns the checked attribute value. Does not change with checked state.
$("#use").prop("checked") //Returns boolean checked state.
$("#use")[0].checked //Returns boolean checked state.
$("#use").is(":checked") //Returns boolean checked state.
Notice the results of .val and .attr do not change. That is because the val property is not dependent on the checked state, and the actual checked attribute in the markup does not update when the checkbox changes. Only the property on the DOM object behind the scenes, which is what the last three methods access.
See jQuery's API documentation on .prop for more info about this.
Upvotes: 3
Reputation: 5469
.val() returns the contents of the value attribute. as it probably is non-null that equates to true.
Also check your casing. JavaScript, css & therefor also jQuery are case sensitive.
Upvotes: 7
Reputation: 13509
You can use the following verify if a checkbox is checked.
var chk = $('#use').attr('checked');
or
var chk = $('#use').is(':checked');
Upvotes: 54