Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to submit unchecked checkbox also

If checkbox is not checked, clicking on form submit button does not submit any data.

Some checkboxes may be not present in form depending on form fields selected by user. So submit controller has no possibility to determine if the unchecked checkbox was present in form or not.

If database contains true for this column, this property is not updated to false. Checkbox name is same as database boolean column name.

How to to force form to submit checkboxes which are in unchecked state or any other idea to set value in database to false if checkbox is not checked but not to change value in database if checkbox is not present in form ?

jquery, jqueryui, asp.net 2 mvc are used

like image 643
Andrus Avatar asked Sep 29 '11 17:09

Andrus


2 Answers

This is a common issue with checkboxes in HTML forms and isn't unique to ASP.NET.

The answer is to have a hidden field that accompanies each checkbox. When the checkbox is modified, use a client-side event to update the hidden field.

The hidden field will always be submitted.

However, since you're using ASP.NET MVC, if you use the HTML.CheckBoxFor helper, it will handle this for you automatically.

like image 85
Steve Morgan Avatar answered Sep 22 '22 00:09

Steve Morgan


This is a very common problem - when checkbox isn't selected it wont send to server value off/ false by itself. Most popular answer that I found was to add hidden field with the same name as checkbox and value = false. But then when someone checked it it sent me two values.

And I didn't like it. This is what I did:

Somewhere in HTML:

<input type="checkbox" name="${name}" onclick="true" >

In JQuery:

First step is to set hidden values on all checkboxes that aren't checked.

$(document).ready(function () {
        $(".checkbox").each(function () {
                 if ($(this).prop("checked") == undefined) {
                    $(this).after("<input type=\"hidden\" name=\"" + $(this).attr("name") + "\" value="off">")
                 }
              }
        )
     });

Secondly we have to react on user clicking the check-box: while unselecting add hidden field, when selecting - remove next sibling in DOM - we expected hidden field there.

WARNING: when check-boxes have common parent you should check if next sibling's type is hidden and then remove it!:

   $(".checkbox").click(function () {
                    if ($(this).prop("checked") == undefined) {
                       $(this).after("<input type=\"hidden\" name=\"" + $(this).attr("name") + "\" value=off>")
                    } else {
                       $(this).next().remove();
                    }
                 }
           );

And it works for me :)

like image 21
Diaes Avatar answered Sep 19 '22 00:09

Diaes