-1

I have tried the below to capture the value "1" on checkbox selection and value "0" on unselection of a checkbox. The Problem I am facing is if I select the checkbox, the value "1" is capturing but if I didn't select the checkbox the value="0" is not captured on form data.

JS:
    <script>
    function setvalue() {
    if (document.getElementById('binary').checked = true) {
       document.getElementById('binary').value='1';
    } else {
        document.getElementById('binary').value='0';
    }
    </script>


HTML:
    <input name="Maximize" id="binary" type="checkbox" value=" ">

2 Answers2

1

Unchecked checkboxes will not be submitted.

Insert a hidden input before the checkbox:

<input name="Maximize" type="hidden" value="0">
<input name="Maximize" type="checkbox" value="1">

However, it's redundant. When you parse the form-data on serverside simply assume a value of 0 when the variable is not set

Dr.Molle
  • 116,463
  • 16
  • 195
  • 201
  • I have tried this. It is capturing only the "0"s . When I select the checkbox the value "1" is not captured – anandbooklet S Aug 29 '14 at 17:07
  • captured by what? when you send the form and the checkbox has been checked, 1 will be submitted, otherwise 0 – Dr.Molle Aug 29 '14 at 17:14
  • No matter I have checked or not, It is always capturing "0"s. Can you please correct my code above and show me how? – anandbooklet S Aug 29 '14 at 17:26
  • Correct, a script wouldn't help here when the control(form-field) is not successful(and a checkbox is only successful when it's checked). See: [successful controls](http://www.w3.org/TR/html401/interact/forms.html#h-17.13.2). My suggestion uses the hidden input(0) as default and when the checkbox(1) is checked it will overwrite the hidden input. No need for a script. – Dr.Molle Aug 29 '14 at 18:49
0

This line

if (document.getElementById('binary').checked = true) {

should be

if (document.getElementById('binary').checked == true) {

or

if (!!document.getElementById('binary').checked) {

no?

Patrick Ferreira
  • 1,983
  • 1
  • 15
  • 31