PDA

View Full Version : Javascript to reset radio button



djmatt
05-04-2009, 11:58 PM
I have a form that has you rate different songs 1, 2, or 3 or blank(no choice). You save that and the next time you load the form, the corresponding radio button is selected. What I want to do is have another button that if, for example, 3 is already chosen (saved), when the page loads, you click this button and just that radio group resets to blank. I don't want to reset the all the songs to blank, just this one. Any help would be appreciated.

felgall
05-05-2009, 01:25 PM
You need to add a fourth hidden field of the same name to the form in order to be able to do that and then select that one from JavaScript to clear the other three. The hidden field must come first so that any selected radio button will override it.

djmatt
05-05-2009, 08:49 PM
Thanks, Felgall. Your solution sounds pretty straight-forward. I modified some other code I found and solved the problem with this onClick:

<img src="../pix/x.gif" title="Click to erase choice" alt="Click to erase choice" onClick="var form = document.forms[0]
for (var i=0; i < form.S1.length; i++) {
if(form.S1[i].checked) {
form.S1[i].checked = false; } }"

For anyone who is not great w/ JS (like me), I am going through each possible radio button choice and setting it to false if it is checked. It is working fine in my own testing - we'll see when I let it loose on the public.

I use php to change "S1" to "S2" and so on which is the name of each song.

felgall
05-06-2009, 02:37 AM
Setting radio buttons to false is not supposed to work and therefore probably doesn't in many browsers (just as all the old push button car radios din't all have a way of pulling out the one button that was in without pushing in one of the others). Setting a hidden "button" to true will force all the visible ones to false in all browsers.

djmatt
05-10-2009, 11:29 PM
Here is what I came up with following your suggestion:

the 1st radio of S11 is blank & hidden. there are 3 the onClick makes S11[0] true. I cut out some of my other code to just show the bare structure.

<input type="radio" name="S11" value="" style="display:none;">
<input type="radio" name="S11" value="A: Barry White">A
<input type="radio" name="S11" value="B: Barry White">B
<input type="radio" name="S11" value="X: Barry White">X
<img src="x.gif" onClick="document.Form.S11[0].checked = true;"> Barry White