Prince Prince - 4 months ago 34
HTML Question

Get the value of a radio button using jquery

I have this portion of code:



var selected = $("#checkout").find("input[type='radio']:checked");
selected.change(function(){
alert(selected.val());
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<div id="checkout">
<p>Checkout Options:</p>
<label for="register">
<input type="radio" name="account" value="register" id="register" checked>
<b>Register Account</b></label>
<br>
<label for="guest">
<input type="radio" name="account" value="guest" id="guest">
<b>Guest Checkout</b>
</label>
</div>





What I want it is to get the value of the selected radio button but with my code I only get the first radio button value, the second radio does not work.
Kindly help me fix the error.

Answer

You need to use this to refer the element inside the callback. So get value by using this.value or $(this).val() method. Although avoid :checked pseudo-class selector otherwise it only selects the first element.

var selected = $("#checkout").find("input[type='radio']");
    selected.change(function(){
        alert(this.value);
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<div id="checkout">
    <p>Checkout Options:</p>
    <label for="register">
        <input type="radio" name="account" value="register" id="register" checked>
        <b>Register Account</b></label>
    <br>
    <label for="guest">
        <input type="radio" name="account" value="guest" id="guest">
        <b>Guest Checkout</b>
    </label>
</div>


You can make it simpler using :radio pseudo-class selector

$("#checkout :radio").change(function() {
  alert(this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<div id="checkout">
  <p>Checkout Options:</p>
  <label for="register">
    <input type="radio" name="account" value="register" id="register" checked>
    <b>Register Account</b>
  </label>
  <br>
  <label for="guest">
    <input type="radio" name="account" value="guest" id="guest">
    <b>Guest Checkout</b>
  </label>
</div>