In this tutorial we will learn how to Get Checked Radio Button Value By id with jQuery. If id of radio button is already known then we can use that id and jQuery val() method to get the value of checked radio button. If id of checked radio button is not known then we will use jQuery attr() method to get the id first.
Table of Contents
jQuery val() Method
jQuery val() Method sets or returns the value of input HTML elements.
In this example val() method is used to get the value of checked radio button using it's id.
jQuery attr() Method
jQuery attr() Method sets or returns the value of the attributes of HTML elements.
In this example attr() method is used to get the id of the checked radio button.
:checked Selector
:checked Selector is used to target or select the checked radio buttons and checkboxes.
In this example :checked Selector is used to select the checked radio button to get it's value.
HTML Code
HTML Code is given below, in this code we have two radio buttons with two labels and a button tag.
<!DOCTYPE html>
<html>
<head>
<title>Get Checked Radio Button Value By id with jQuery</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<label for="m1">Male</label>
<input id="m1" type="radio" name="gender" value="male">
<label for="f1">Female</label>
<input id='f1' type="radio" name="gender" value='female'>
<button id="btn">Get Value</button>
<script src="script.js"></script>
</body>
</html>
JQuery Code
JQuery Code is given below, the code is executed whenever button is clicked. This is done using jQuery click() method.
jQuery attr() method is first used to get the id of the checked radio button.
Then val() method is used to get the value of that radio button by it's id.
Take a look at the code given below.
<script>
$(document).ready(function(){
$('#btn').click(function(){
var id = $('input[name=gender]:checked').attr('id');
var value = $('#'+id).val();
alert(value);
});
});
</script>
If id of checked radio button is already known
<script>
$(document).ready(function(){
$('#btn').click(function(){
var value = $('#m1:checked').val();
alert(value);
});
});
</script>
In above code we have used id to get the value of checked radio button. But this is not a very practical method since id is not known in most cases.
It's solution is given below.
If id of checked radio button is not known
<script>
$(document).ready(function(){
$('#btn').click(function(){
var id = $('input[name=gender]:checked').attr('id');
var value = $('#'+id).val();
alert(value);
});
});
</script>
First we get the id of checked radio button then it's value is retrieved.
Demo
Video Tutorial
Watch video tutorial on How To Get Checked Radio Button Value By id in jQuery.