2
\$\begingroup\$

Task

Create a matrix of checkboxes. The user must be able to select only 1 checkbox in a row or unselect all of them.

enter image description here

Solution

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
    <script type="text/javascript">
      function switch_checkbox(id_selected, id_pair)
      {
           //if the current checkbox is checked - uncheck the 2-nd checkbox in this row
          if(document.getElementById(id_selected).checked == true)
          {
              document.getElementById(id_pair).checked = false;
          }
      }
    </script>
  </head>
  <body>
    <form method="post" id="" action="send.php">
      <input type="checkbox" name="group1[]" id="1-1" value="1-1" onChange="switch_checkbox('1-1', '1-2');"/>
      <input type="checkbox" name="group2[]" id="1-2" value="1-2" onChange="switch_checkbox('1-2', '1-1');"/>
      <br />
      <input type="checkbox" name="group1[]" id="2-1" value="2-1" onChange="switch_checkbox('2-1', '2-2');"/>
      <input type="checkbox" name="group2[]" id="2-2" value="2-2" onChange="switch_checkbox('2-2', '2-1');"/>
    </form>
  </body>
</html>

As you see, the solution is very primitive. Is it possible to make it even simpler?

\$\endgroup\$
  • \$\begingroup\$ why not change to radio buttons? \$\endgroup\$ – ratchet freak Dec 19 '13 at 9:37
  • \$\begingroup\$ @ratchetfreak Because when you select one radio button, you can't unselect all of them. \$\endgroup\$ – user4035 Dec 19 '13 at 9:51
1
\$\begingroup\$

Assuming an unchecked starting condition you can eliminate a parameter and thus drop the conditional:

function switch_checkbox(id_pair)
{
    document.getElementById(id_pair).checked = false;
}

...

<input type="checkbox" name="group1[]" id="1-1" value="1-1" onChange="switch_checkbox('1-2');"/>
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.