mercredi 27 avril 2016

JavaScript - Select radio button if any checkbox is checked

I'm trying to write JavaScript code where a radio button should be populated if a checkbox is checked.

Following is the HTML code:

<form>
   <h3>Radio Buttons</h3>
   <input type="radio" name="radio1" id="radio1"> Radio 1
   <br>
   <input type="radio" name="radio2" id="radio2">Radio 2
   <br>
   <br>

   <h3>Checkbox Groups</h3>

   <h4><u>Group 1</u></h4>
   <p align="center"><u>PD</u></p>
   <ul>
      <li>
         <input id="pdcb" type="checkbox" name="G1PD1" onclick="validate()">G1 PD1</li>
      <li>
         <input id="pdcb" type="checkbox" name="G1PD2" onclick="validate()">G1 PD2</li>
   </ul>
   <p align="center"><u>ID</u></p>
   <ul>
      <li>
         <input id="idcb" type="checkbox" name="G1ID1" onclick="validate()">G1 ID1</li>
      <li>
         <input id="idcb" type="checkbox" name="G1ID2" onclick="validate()">G1 ID2</li>
   </ul>

   <h4><u>Group 2</u></h4>
   <p align="center"><u>PD</u></p>
   <ul>
      <li>
         <input id="pdcb" type="checkbox" name="G2PD1" onclick="validate()">G2 PD1</li>
      <li>
         <input id="pdcb" type="checkbox" name="G2PD2" onclick="validate()">G2 PD2</li>
   </ul>
   <p align="center"><u>ID</u></p>
   <ul>
      <li>
         <input id="idcb" type="checkbox" name="G2ID1" onclick="validate()">G2 ID1</li>
      <li>
         <input id="idcb" type="checkbox" name="G2ID2" onclick="validate()">G2 ID2</li>
   </ul>
</form>

So here's what I want the JavaScript to do: if any of the PD checkboxes under Group 1 and/or Group 2 are checked, the Radio button Radio 1 should get populated. If any of the ID checkboxes under Group 1 and/or Group 2 are checked, then the radio button Radio 2 should get populated. Similarly, if none of the checkboxes are checked, then no radio button should get populated.

So far, I've written the following JS code:

function validate()
{
    if(document.getElementById("pdcb").checked) //if pdcb checkbox(es) is/are checked
  { 
    document.getElementById("radio1").checked = true;
    document.getElementById("radio2").checked = false;
  }  
  else if (document.getElementById("idcb").checked) //if idcb checkbox(es) is/are checked
  { 
    document.getElementById("radio1").checked = false;
    document.getElementById("radio2").checked = true;
  }
  else //if no checkbox is checked, then don't populate any radio button
  {
    document.getElementById("radio1").checked = false;
    document.getElementById("radio2").checked = false;
  }

}

PS: I need the code to be in pure JavaScript. I can't use jQuery

Could anyone help me out here?

Thanks in advance!




Aucun commentaire:

Enregistrer un commentaire