function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Jonny SimmoJonny Simmo 

How can I reference Visualforce radio button values in JavaScript?

Hi,

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
 
KaranrajKaranraj
Johny, Try the below code,
 
<apex:page >
<script>
    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);
         }
       }
     }
  </script>
    <apex:form id="theForm">
         
        <apex:selectRadio id="theRadio" onchange="radioval();">
               <apex:selectOption itemValue="test1" itemLabel="test1" />
               <apex:selectOption itemValue="test2" itemLabel="test2" />
         </apex:selectRadio>
   </apex:form>
</apex:page>

 
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?