Working with Radio buttons and jQuery

Working with Radio buttons and jQuery Radio buttons are one of the essential HTML elements that you can find in almost any website that contains a form for users to enter data. In this blog today we will do the following:

  • Add radio buttons dynamically using jQuery
  • And, get the value and text of the selected radio button using jQuery

First you need a standard boiler plate html page that has a reference to the jQuery library. For this example we will use the Google jQuery CDN to pull the library on our page. At this stage, you page should look like this:

<html>  
    <head>
         <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
    </head>
    <body>
    </body>
</html>  

Now we can add our basic html elements. The page will consist of 2 buttons and 1 div where the radio buttons will eventually be displayed. Within the body add the following html:

<button id="btnCreate">Create</button>  
<button id="btnSelect">Get</button>  
<div id="dvOptions"></div>  

Finally, between the closing </body> and closing </html> tags add the following javascript code:

$('#btnCreate').on('click', function (e) {
    var $greetingOptions = $('#dvOptions');
    $greetingOptions.empty();
    e.preventDefault();
    var arrayValues = ["Good Morning", "Good Afternoon", "Good Evening", "Good Night"];
    for (var i = 0; i &lt; arrayValues.length; i++) {
        if(i === 0)
        {
            $greetingOptions.append($('<input type="radio" name="greetings" value="' + i + '" checked>' + arrayValues[i] + '</input><br />'));
        }
        $greetingOptions.append($('<;input type="radio" name="greetings" value="' + i + '">' + arrayValues[i] + '</input&gt;&lt;br />'));
    }
});

$('#btnSelect').on('click', function (e) {
    var testValue = $('#dvOptions input:radio:checked').val();
    var testText = $('#dvOptions input:radio:checked')[0].nextSibling.data;
    alert(testValue + " - " + testText);
});

The first method uses a string array in order to populate the radio buttons with values and text. We also use the .append method to add the radio buttons to the DOM and make them visible. The first time that we iterate through the array, we also set the radio button to checked so that the user can see the first option pre-selected when presented with the radio buttons. This is optional and you can of course opt out from having any radio buttons implemented.

The second method uses jQuery in order to retrieve the value and the test of the selected radio button and displays an alert (message box) with the selected values. For me, the trickiest part was getting the selected text, especially if it is different from the radio button value itself.

You can see a working version of this code on jsFiddle

Happy coding…


  • Share this post on
comments powered by Disqus