One way sign

How to detect which radio button is selected

Hello, if you need to detect which radio element is selected, then this article may help. We will show how to get value of the selected radio button from the group of such elements in your HTML form. For the beginning, we will use jQuery framework since it's very popular and easy to use solution.

Here is the code:

<form id="example-form">
    <label><input type="radio" name="color" value="red" /> Red</label><br/>
    <label><input type="radio" name="color" value="green" /> Green</label><br/>
    <label><input type="radio" name="color" value="blue" /> Blue</label><br/>
    <input type="submit" value="Submit" />
</form>

This is a simplest form with three radio button elements. Users are asked to choose color and submit the data by clicking on the button.

There, as you probably already noticed, we wrapped our input elements by the label tags, that's because we want our text to be clickable. This is a good usability experience for your users and you may apply the same design pattern on your page as well, it may be much easier for site visitors to click on desired elements. Otherwise, only the radio button can be clickable.

Also, it's important to note that all radio elements, that belong to specific collection, must have exactly the same name attribute. If your HTML page contains several forms, you may need to use different name value for each group.

Now, it's time to show the JavaScript code:

$( '#example-form input[type="submit"]' ).click( function() {
    alert( 'Value: ' + $( '#example-form input[name="color"]:checked' ).val() );
} );

We have added a handler for the click event that displays alert with information on what element is selected at the moment.

All JavaScript code must be placed after the HTML form inside of block, otherwise it will not work. If that's not the desired design, then you may want to consider using another option. Custom code may be placed inside of handler for the document ready event, so it's executed once HTML page is fully loaded, see how it can be done below.

(function( $ ) {
    $( document ).ready( function() {
        $( '#example-form input[type="submit"]' ).click( function() {
            alert( 'Value: ' + $( '#example-form input[name="color"]:checked' ).val() );
        } );
    });
})( jQuery );

In our code block, you can see the specific code where we get current value. We are using jQuery selector that finds only checked radio button elements, that's because of the ":checked" rule.

$( '#example-form input[name="color"]:checked' ).val()

In addition, you can select radio button elements in your HTML code by type, which may be more convenient and flexible solution, since you won't need to modify your JavaScript code if the radio button group is renamed.

$( '#example-form input[type="radio"]:checked' ).val()

Now, we'll describe another similar method of detecting state of the element. Instead of getting value of the input element directly, you can check if the specific radio button is currently selected or not by using is() method with the proper selector. You may find that this case is also useful in some conditions.

But please pay attention, you will have to provide unique and different ID for each radio button, see how it's done in our new and refined code example:

<form id="example-form">
    <label><input type="radio" name="color" id="color-red" value="red" /> Red</label><br/>
    <label><input type="radio" name="color" id="color-green" value="green" /> Green</label><br/>
    <label><input type="radio" name="color" id="color-blue" value="blue" /> Blue</label><br/>
    <input type="submit" value="Submit" />
</form>

The JavaScript code will be:

$( '#example-form input[type="submit"]' ).click( function() {
    if ( $( '#example-form #color-red' ).is(':checked') ) {
        alert( 'Red color is selected' );
    } else {
        alert( 'Red color is not selected' );
    }
} );

If the red input element is selected in the form, then we display appropriate message on the screen.

Or another way is to use the prop() method, as shown below:

$( '#example-form input[type="submit"]' ).click( function() {
    if ( $( '#example-form #color-red' ).prop('checked') ) {
        alert( 'Red color is selected' );
    } else {
        alert( 'Red color is not selected' );
    }
} );

Now, we would like to show completely different strategy. If checking state of the specific radio button is not a suitable solution, you can add event handler that will be triggered once any radio element is changed by site visitor.

Here is example in jQuery:

$( '#example-form input[type="radio"]' ).change( function() {
    alert( 'Value: ' + $( this ).val() );
} );

But you have to know that such event handlers are called immediately after user makes a decision and clicks on desired radio button. There is no need to put this code into handler for the click event on submit button. Usually, this method can be used to change some information on screen when active radio element is changed.

Finally, to make this article complete, we would like to show also how to check state of radio button in plain JavaScript code, so you can see how it can be done without using any additional frameworks.

The HTML code is the same as in previous examples, but just in case, we are adding it here again:

<form id="example-form">
    <label><input type="radio" name="color" id="color-red" value="red" /> Red</label><br/>
    <label><input type="radio" name="color" id="color-green" value="green" /> Green</label><br/>
    <label><input type="radio" name="color" id="color-blue" value="blue" /> Blue</label><br/>
    <input type="submit" value="Submit" />
</form>

The JavaScript code is here:

if ( document.getElementById( 'color-red' ).checked ) {
    alert( 'Red color is selected' );
} else if(document.getElementById( 'color-green' ).checked ) {
    alert( 'Green color is selected' );
} else if(document.getElementById( 'color-green' ).checked ) {
    alert( 'Blue color is selected' );
}

Also, you can get radio elements by name, but then you'll have to iterate over the array and check which element is selected or not, see our new example below:

var radioElements = document.getElementsByName('color');

for ( var i = 0; i < radioElements.length; i++ ) {
    if ( radioElements[i].checked ) {
        alert( 'Color: ' + radioElements[i].value );
    }
}

As you can see, there are many different ways to check state of the input radio buttons. jQuery method is a quick solution and will work in most cases. But plain JavaScript code is an option for those who can not use additional frameworks in their projects. As a developer, you need to evaluate each method and choose the one that suits your needs best and works flawlessly.

Related Articles

Contact us text

Simple PHP contact form

Source code user service

What is the correct JSON content type?

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *