views:

66

answers:

3

So I have the following JavaScript code:

<script type="text/javascript">
    function clearRadioButtons()
    {
        document.getElementById("radiobutton1").checked="";
        //etc for more radio buttons
    }
</script>

And then in my form, I have the following code:

<select name="whatever" onclick="clearRadioButtons()">
    <option onclick="clearRadioButtons()"></option>
    //and so on and so forth for <option> tags with values
</select>

The problem is that the function is never actually called even if I click on the select or option elements. If I call the JS function in my browser's debugger, it works fine, but the event is not being triggered. What am I doing wrong here? I have the feeling that it's pretty simple, but who knows.

TIA.

+2  A: 

I think you are wanting to use the onchange event on your select element.

function clearRadioButtons () {
    document.getElementById("radiobutton1").checked="";
    //etc for more radio buttons
}

window.onload = function () {
  //Event binding... 
  document.getElementById('whatever').onchange = clearRadioButtons;
};


<select id="whatever" name="whatever">
    <option></option>
    ...
</select>
CMS
Nice, thanks - that worked perfectly.
benjy
You're welcome @benjy, note that I also encourage you to do the event binding programmatically, that will give you cleaner markup and code easier to debug/maintain.
CMS
+2  A: 

You pass in the function as

  clearRadioButtons().

The brackets cause the function to be executed right on. You should use clearRadioButtons, without the (). That way, it passes a reference to the function.

Ikke
+1  A: 

What Ikke said, but also I should point out that you shouldn't be setting the checked property to "" since it is the DOM property and not the element attribute which you are modifying - set it to a boolean.

annakata
Agree, should be set to false or removed via elem.removeAttribute
CMS