jQuery – Determine which radio box is checked

Assume you have the following HTML form:

<form id="weather-form">
  <input name="weather" type="radio" value="sunny">Sunny
  <input name="weather" type="radio" value="cloudy">Cloudy
  <input name="weather" type="radio" value="rainy">Rainy
</form>

 

To get the checked value using jQuery:

var result = $("#weather-form input[name=weather]:checked").val();
// OR
var result = $("input[name=weather]:checked", "#weather-form").val();

 

Complete Example:

<!DOCTYPE html>
<html>
<head>
  <title>jQuery - Get radio input value</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
  <script type="text/javascript">
  $(document).ready(function () {
    $("#btn").click(function() {
      var result = $("#weather-form input[name=weather]:checked").val();
      alert(result);
    });
  });
  </script>
</head>
<body>
  <form id="weather-form">
    <input name="weather" type="radio" value="sunny">Sunny
    <input name="weather" type="radio" value="cloudy">Cloudy
    <input name="weather" type="radio" value="rainy">Rainy
  </form>
  <button id="btn">Click me</button>
</body>
</html>

 

Done =)

Reference: StackOverflow – How can I get which radio is selected via jQuery?

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.