Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 3 checkbox always returns true, even if unchecked

Tags:

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?

like image 666
Heinrich Walkenshaw Avatar asked Oct 06 '11 12:10

Heinrich Walkenshaw


People also ask

Why is checkbox always true?

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.

What is the value of checkbox when unchecked?

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.

How check if checkbox is unchecked?

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.

How do I make a checkbox value true?

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 .


1 Answers

You can use the following verify if a checkbox is checked.

var chk = $('#use').attr('checked'); 

or

var chk = $('#use').is(':checked');  
like image 111
Nicholas Murray Avatar answered Oct 11 '22 19:10

Nicholas Murray