get value from radio group using jquery
Asked Answered
W

3

84

I am trying to get value of radio group with name managerelradio. My html code for this radio group is.

 <label><input type="radio" name="managerelradio" value="Yes" id="Add">Add</label>
 <label><input type="radio" name="managerelradio" value="No" id="Remove">Remove</label>

and Jquery for this is..

    var manageradiorel = $('input[name = "managerelradio"]:checked' , '#managechildform').val();
 alert(manageradiorel);

its showing me undefined.

Though I have also tried it as.

 var manageradiorel = $('input[name = "managerelradio"]:checked').val();
 alert(manageradiorel);

But still I am getting undefined value.

Withindoors answered 11/10, 2011 at 8:51 Comment(1)
Can you post HTML too? .That will help us to understand the problemBraces
B
153

Try this

var manageradiorel = $("input:radio[name ='managerelradio']:checked").val();
alert(manageradiorel);

Plese check this DEMO ..it will work fine

Note: One of your radio button must be selected. Otherwise it will return undefined

You can use checked attribute to make a radio button selected as default

Braces answered 11/10, 2011 at 8:55 Comment(5)
also it must be placed in onchange event, i guessVolin
@Shameer, I dont think so . You can see the demoBraces
It works for me (even without onchange event), this should be the accepted answer!Disposure
+1, works. For the case of not having more than one button group, one can leave the name specification in the selector away.Bores
It would be nice if jQuery was smart enough to figure out that $("#managerelradio").val() as looking for the value of the radiobutton group, but since it isn't that smart, at least there's logic in the construction of this selector...Sst
S
17

It works for me

$('input[name="managerelradio"]').on('change', function(e) {

    var manageradiorel = e.target.value;
    alert(manageradiorel);

});

Exaple here

Sudarium answered 11/10, 2011 at 8:59 Comment(2)
Though its work if I use change function on radio group but it won't work if I put in some other change function like on drop down change.Withindoors
@Rahul: Your one of your radio button must selected to get the value.review my update herelinkSudarium
D
10

A small jQuery extension to make this a little easier:

jQuery.fn.extend({
    groupVal: function() {
        return $(this).filter(':checked').val();
    }
});

// Usage:
$("input[name='managerelradio']").groupVal();

// Or even:
$("[name='managerelradio']").groupVal();
Deuterium answered 30/10, 2015 at 16:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.