Tuesday, March 15, 2011

Getting radio button value from radio group using jQuery

Getting radio button value from a group of radio buttons is an easy task using jQuery. All you have to do is to apply the correct selector. If we have a group of radio buttons named: radioGroup all if we have to do is:
$('input[name=radioGroup]:checked').val();
Let's have a look how it looks on a real HTML page containing 3 radio buttons and a check button. By clicking the “Check Value” button we will open an alert popup showing the selected radio value:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title> TEST </title>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
</head>
<body>  
  <input type="radio" id="inpSmall" name="radioGroup" value="small" checked><label for="inpSmall">Small</label><br>
  <input type="radio" id="inpMedium" name="radioGroup" value="medium"><label for="inpMedium">Medium</label><br>
  <input type="radio" id="inpLarge" name="radioGroup" value="large"><label for="inpLarge">Large</label><br><br>
  <input value="Check Value" type="button" onclick="alert('Radio group value: ' + $('input[name=radioGroup]:checked').val());">
</body>
</html>

No comments:

Post a Comment