My javascript is a little rusty and I've just spent a few hours trying to solve this problem: How do you copy the checked value of a radio button to a set/group of radio buttons?
I have this radio button group as the master group, the one that when I change what's checked I want it to modify the rest of the other set of radio buttons when a button was clicked:
<input type="radio" name="master" value="1"> Yes
<input type="radio" name="master" value="0"> No
<input type="radio" name="master" value=""> --
<input type="button" name="radiocopy" onclick="copydown()" value="Change All" ></button>
And the other groups are found in some rows of data and one of the columns requires a choice to be made: Yes, No, or missing.
<input type="radio" name="slaveRow1" value="1"> Yes
<input type="radio" name="slaveRow1" value="0"> No
<input type="radio" name="slaveRow1" value=""> --
<input type="radio" name="slaveRow2" value="1"> Yes
<input type="radio" name="slaveRow2" value="0"> No
<input type="radio" name="slaveRow2" value=""> --
<input type="radio" name="slaveRow3" value="1"> Yes
<input type="radio" name="slaveRow3" value="0"> No
<input type="radio" name="slaveRow3" value=""> --
Now what I wanted was that when I set the master to Yes, the rest of the radio buttons would change to Yes as well when I click the Change All button. Here's what I wrote:
function copydown(){
var fm = document.forms["thenameofyourform"];
//find out which master radio button is checked and assign value to masterValue
var masterValue = null;
for(i = 0; i < fm.elements['master'].length; i++){
if(fm.elements['master'][i].checked == true)
masterValue = fm.elements['master'][i].value;
}
//loop through all the form elements in the page
for(i = 0; i < fm.elements.length; i++){
//select only the radio buttons
if( fm.elements[i].type == "radio" && fm.elements[i].name.indexOf("slaveRow") != -1){
//check the value of each slave radio button and if it matches the
//checked value of the master then check it
if(fm.elements[i].value == masterValue)
fm.elements[i].checked = true;
}
}
}
That seemed to do the trick. I must admit my Javascript is rusty. If you don't want to implement this with a button you can add a listener to the master radio buttons group.
No comments:
Post a Comment