H Dindi
H Dindi

Reputation: 1552

Jquery get value of the current selected radio button

I have the following radio buttons :

<label>Referred to Health Facility</label>
    <input required name="Health_Ref" type="radio" class="wellness_center radiostyle Health_Ref" id="Health_Ref" value="Yes">
    <div class="radiolabel">Yes</div>
    <input name="Health_Ref" type="radio" required class="wellness_center radiostyle Health_Ref" id="Health_Ref" value="No" checked="checked">
    <div class="radiolabel">No</div>

And below is my jquery function to get the values :

$(document).ready(function () {
        $(".Health_Ref").click(function () {
            var value = $(".Health_Ref").val();
            alert(value);
        });
    });

The value being returned when i click the first or second button is for the first button which is Yes , how is the best way to implement the jquery function so that I can get the value of the clicked radio button ?

Upvotes: 0

Views: 2806

Answers (2)

Fredrik Andersson
Fredrik Andersson

Reputation: 121

var value = $(".Health_Ref:checked").val();

This selects only the currently checked radio button.

the same works for checkboxes.

Upvotes: 0

Jess
Jess

Reputation: 25029

You may want to try adding :checked to your jquery selector. Documentation for :checked.

Option 1 with :checked

$(document).ready(function () {
    $(".Health_Ref").click(function () {
        var value = $(".Health_Ref:checked").val();
        alert(value);
    });
});

Option 2 with $(this)

I made the code simpler. this is the value of the element in an event handler, so you can simply use $(this) to turn the element into a jQuery object.

$(document).ready(function () {
    $(".Health_Ref").click(function () {
        var value = $(this).val();
        alert(value);
    });
});

Code Pen: http://codepen.io/anon/pen/wKgBGN

Upvotes: 2

Related Questions