views:

100

answers:

2

I have the following code snippet embedded into some of my divs so when those divs get clicked a certain radio button gets checked.

onclick="document.g1.city[0].checked=true;"

However I would like to convert the above call to a function call like below:

onclick="checkRadioButton(city[0]);"

And the function will be something like this

function checkRadioButton(input){
    document.g1.input.checked=true;
}

Is there a way I can accomplish this?

A: 
onclick="checkRadioButton(document.g1.city[0]);"

checkRadioButton(var input){
    input.checked=true;
}

You can also reduce the need for supplying document.g1.city[0] if, for example, every DIV that you mark thusly has an attribute "radioID", and the value of the attribute must match the ID given to the radio button:

onclick="checkRadioButton(this);"

checkRadioButton(var div){
    document.getElementById(div.radioID).checked=true;
}
DVK
In xhtml I'm supposed to use every id only once on every page right? So won't this code require invalid xhtml where multiple elements will have the same id which is `radioID`: "document.getElementById(div.radioID).checked=true;"
Haluk
+3  A: 

You can write any Javascript code inside the onclick attribute. Remember that city[0] is not defined anywhere. To access it, you must specify the full document.g1.city[0]. So the onclick becomes:

onclick="checkRadioButton(document.g1.city[0]);"

Inside your function, you are already receiving the element, and don't have to retrieve it from the document again. You could directly set it's checked property:

function checkRadioButton(input) {
   input.checked = true;
}
Anurag
You need to remove the `var` keyword on the function argument list.
CMS
thanks for pointing that out @CMS
Anurag