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?
Explanation: you were reading the value of the checkbox which is always true, you need to check whether its checked attribute is checked or unchecked. I used the ternary operator to check check whether it's checked or not You could have also used $("#status").is(":checked") but it is slower. Show activity on this post.
Note: If a checkbox is unchecked when its form is submitted, there is no value submitted to the server to represent its unchecked state (e.g. value=unchecked ); the value is not submitted to the server at all.
Checking if a checkbox is checked First, select the checkbox using a DOM method such as getElementById() or querySelector() . Then, access the checked property of the checkbox element. If its checked property is true , then the checkbox is checked; otherwise, it is not.
val( checkbox[0]. checked ? "true" : "false" ); This will set the value of the checkbox to "true" or "false" ( value property is a string) , depending whether it's unchecked or checked .
You can use the following verify if a checkbox is checked.
var chk = $('#use').attr('checked');
or
var chk = $('#use').is(':checked');
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