Site icon ParallelCodes

jQuery – Get Selected Radio Button value

The :checked selector works for checkboxes, radio buttons, and options of select elements. To retrieve only the selected options of select elements, use the :selected selector. The :checked selector in jQuery is used to retrieve the selected option from the radio button group. In this example we will first create a radio button option group of different roles and retrieve the selected option from the group.

Syntax:

$('input[name="radioGroupName"]:checked').val();

This will return the selected option from the radio group. For example let’s say the group name is jobRoles so the code would be

$('input[name="jobRoles"]:checked').val();

Example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>JQuery - Get value</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">

</head>
<body style="padding:10px">

<h2>Select your role:</h2>

<input type="radio" name="role" value="SCRUM Master">SCRUM Master<br/><br />
<input type="radio" name="role" value="Database Administrator">Database Administrator<br /><br />
<input type="radio" name="role" value="Software Developer">Software Developer<br /><br />
<input type="radio" name="role" value="QA Tester">QA Tester<br /><br />
<input type="radio" name="role" value="Product Manager">Product Manager<br /><br />

<label id="lblSelectedOption">You have selected no roles yet</label><br/><br />
<input type="button" id="btnSubmit" value="Submit">

<script>
$(document).ready(function () {
watchSelectedValue();
$('#btnSubmit').click(() => {

alert(getSelectedValue());
});

});

function watchSelectedValue()
{
$("input").on("click", function () {
getSelectedValue();
});
}

function getSelectedValue()
{

var selectedOption = $('input[name="role"]:checked').val();
if (selectedOption) {
$('#lblSelectedOption').html("You have selected " + selectedOption)
return selectedOption;
}
return "No option selected"

}
</script>
</body>

</html>

Output:

Also see:
jQuery: How to Get, Set and Remove Attribute

HTML showing Notifications using jQuery

jQuery DataTable custom dark theme

Custom CSS designs for jQuery DataTable.


Exit mobile version