While submitting a form or validating a form using the jQuery, we can get all the values of form easily but radio button works differently and we need some extra efforts to fetch the value of radio input. So in this article i will demonstrate to fetch the value of radio button.
In this example i will use a question to select a radio button with 4 options.
$(“input[name=’answer’]:checked”).val()
Get radio input value using name
In the example we will get the value using name attribute of input.
<!DOCTYPE html>
<html>
<head>
<title>Get value of selected radio button with Jquery - Readerstacks.com</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<input type="radio" name="answer" value="1"> 1
<input type="radio" name="answer" value="4"> 4
<input type="radio" name="answer" value="7"> 7
<input type="radio" name="answer" value="8"> 8
<button>Submit/button>
<script type="text/javascript">
$("button").click(function(){
var val = $("input[name='answer']:checked").val();
alert(val);
});
</script>
</body>
</html>
Get radio input value using class
In this example we will get the value using class and :checked
<!DOCTYPE html>
<html>
<head>
<title>Get value of selected radio button with Jquery - Readerstacks.com</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<input type="radio" class='answer_radio' name="answer" value="1"> 1
<input type="radio" class='answer_radio' name="answer" value="4"> 4
<input type="radio" class='answer_radio' name="answer" value="7"> 7
<input type="radio" class='answer_radio' name="answer" value="8"> 8
<button>Submit/button>
<script type="text/javascript">
$("button").click(function(){
var val = $(".answer_radio:checked").val();
alert(val);
});
</script>
</body>
</html>