Reputation: 193
I want to know if there is a clever way to select all radio buttons from diferent groups at once.
It's an old site, so i cant use jquery.
This is what I got so far.
I put the code on codepen, its look pretty simple to me, but I think maybe there are some easiest way to achieve the same results.
HTML:
<form name="form1">
<input type="radio" name="group1" value="1">Yes<br />
<input type="radio" name="group1" value="0">No<br />
<input type="radio" name="group2" value="1">Yes<br />
<input type="radio" name="group2" value="0">No<br />
<input type="radio" name="group3" value="1">Yes<br />
<input type="radio" name="group3" value="0">No
<br />
<br />
<input type="radio" name="group4" value="1" onclick="selectAll(form1)">All Yes<br />
<input type="radio" name="group4" value="0" onClick="selectAll(form1)" >All No
</form>
JAVASCRIPT:
<script type="text/javascript">
function selectAll(form1) {
var check = document.getElementsByName("group4"),
radios = document.form1.elements;
if (check[0].checked) {
for( i = 0; i < radios.length; i++ ) {
if( radios[i].type == "radio" ) {
if (radios[i].value == 1 ) {
radios[i].checked = true;
}
}
}
} else {
for( i = 0; i < radios.length; i++ ) {
if( radios[i].type == "radio" ) {
if (radios[i].value == 0 ) {
radios[i].checked = true;
}
}
}
};
return null;
}
</script>
Upvotes: 1
Views: 6908
Reputation: 11
Try this.You need to pass current page as an parameter onclick="selectAll(this).like this
<form name="form1">
<input type="radio" name="group1" value="1">Yes<br />
<input type="radio" name="group1" value="0">No<br />
<input type="radio" name="group2" value="1">Yes<br />
<input type="radio" name="group2" value="0">No<br />
<input type="radio" name="group3" value="1">Yes<br />
<input type="radio" name="group3" value="0">No
<br />
<br />
<input type="radio" name="group4" value="1" onclick="selectAll(this)">All Yes<br />
<input type="radio" name="group4" value="0" onClick="selectAll(this)" >All No
</form>
<script type="text/javascript">
function selectAll( check ) {
var radio, i=0;
while( radio=check.form.elements[i++] )
if( radio.type == "radio" && radio.value == check.value )
radio.checked = true;
};
</script>
Upvotes: 1
Reputation: 12380
If you change the onclick to selectAll(this)
you can get away with this:
function selectAll( check ) {
var radio, i=0;
while( radio=check.form.elements[i++] )
if( radio.type == "radio" && radio.value == check.value )
radio.checked = true;
};
Upvotes: 0