← W4DEV JOURNAL

jQuery On Change Radio value

Getting the value of the selected radio field using jQuery isn’t tough. To get the selected radio field value we can use the following code, replacing the name radio_input with your own

<script>
    var selected_radio_value = $("input[name='radio_input']:checked").val();
</script>

We have used the radio name, because logically each radio in a group won’t have the same ID. However, it can also be retrieved with a class name.

<script>
    var selected_radio_value = $(".my_radio_input:checked").val();
</script>

To get the radio button value when it changes, you can bind to the jQuery change event

<script>
$("input[name='radio_input']").on('change', function(){
    var selected_radio = $("input[name='radio_input']:checked").val();
    if (selected_radio == 'hello_world'){
        // do something
    }
});
</script>

Find some more examples on https://api.jquery.com/radio-selector/.

Filed under

KEEP EXPLORING

More practical tools for WordPress.

Browse the complete journal or find a focused plugin for your next project.