+ Start a Discussion
Jonny SimmoJonny Simmo 

How can I reference Visualforce radio button values in JavaScript?


I'm hoping this is an easy thing to do?

Within my Visualforce page I have a radio button, and I want to reference the values of the radio button within a JavaScript function within the same page. How can I do this?

I am not picking any of the Radio Button options by default so when the user clicks Submit I want to check that they have selected at least one option.

Many thanks
Johny, Try the below code,
<apex:page >
    function radioval()
      var theRadioButton = document.getElementsByName('{!$Component.theForm.theRadio}');
      for (var i = 0; i < theRadioButton.length; i++) 
        if (theRadioButton[i].checked) {
           alert('Selected value: ' + theRadioButton[i].value);
    <apex:form id="theForm">
        <apex:selectRadio id="theRadio" onchange="radioval();">
               <apex:selectOption itemValue="test1" itemLabel="test1" />
               <apex:selectOption itemValue="test2" itemLabel="test2" />

Jonny SimmoJonny Simmo
Thanks for the reply Karanraj and the code example.

I have tried this but it doesn't seem to work?

I put a couple more alerts in the code, and it doesn't ever go into the for loop?

I wonder if it is retreiving the radiobutton correctly?