I already asked a different question here: JavaScript - Select radio button if any checkbox is checked
I had another question so I am creating a new question for this. I was told to do the same. Hence, the new question. Hope it's alright.
I'm able to populate the radio button Radio 1
if any PD checkbox in Groups 1 and 2 are checked. Similarly, I'm also able to populate the radio button Radio 2
if any ID checkbox in Groups 1 and 2 are checked.
Following is the HTML:
<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 class="pdcb" type="checkbox" name="G1PD1" onclick="validate()">G1 PD1</li>
<li>
<input class="pdcb" type="checkbox" name="G1PD2" onclick="validate()">G1 PD2</li>
</ul>
<p align="center"><u>ID</u></p>
<ul>
<li>
<input class="idcb" type="checkbox" name="G1ID1" onclick="validate()">G1 ID1</li>
<li>
<input class="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 class="pdcb" type="checkbox" name="G2PD1" onclick="validate()">G2 PD1</li>
<li>
<input class="pdcb" type="checkbox" name="G2PD2" onclick="validate()">G2 PD2</li>
</ul>
<p align="center"><u>ID</u></p>
<ul>
<li>
<input class="idcb" type="checkbox" name="G2ID1" onclick="validate()">G2 ID1</li>
<li>
<input class="idcb" type="checkbox" name="G2ID2" onclick="validate()">G2 ID2</li>
</ul>
</form>
Following is the JS code:
function validate()
{
var pdcbClass = document.getElementsByClassName("pdcb");
var idcbClass = document.getElementsByClassName("idcb");
console.log(this);
for (var i = 0; i < pdcbClass.length; i++)
{
if (pdcbClass[i].checked == true)
{
document.getElementById("radio1").checked = true;
document.getElementById("radio2").checked = false;
}
}
for (var i = 0; i < idcbClass.length; i++)
{
if (idcbClass[i].checked == true)
{
document.getElementById("radio1").checked = false;
document.getElementById("radio2").checked = true;
}
}
var pdcbClass2 = document.getElementsByClassName("pdcb");
var idcbClass2 = document.getElementsByClassName("idcb");
console.log(this);
//if none of the checkboxes are checked, don't populate radio buttons
for (var i = 0; i < pdcbClass2.length; i++)
{
if (pdcbClass2[i].checked == false)
{
document.getElementById("radio1").checked = false;
document.getElementById("radio2").checked = false;
}
}
for (var i = 0; i < idcbClass2.length; i++)
{
if (idcbClass2[i].checked == false)
{
document.getElementById("radio1").checked = false;
document.getElementById("radio2").checked = false;
}
}
}
Now, my question is how would I get the radio buttons to not get populated if none of the checkboxes are checked?
PS: I need to write this in pure JavaScript. I cannot use jQuery.
Aucun commentaire:
Enregistrer un commentaire