Ccna final exam - java, php, javascript, ios, cshap all in one. This is a collaboratively edited question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
Tuesday, May 29, 2012
How can I get which radio is selected via jQuery?
I have two radio buttons and want to post the value of the selected one, how can I get the value with jQuery?
To get the value of the selected radioName item of a form called 'myForm':
ReplyDelete$('input[name=radioName]:checked', '#myForm').val()
Use this..
ReplyDelete$("#myform input[type='radio']:checked").val();
The example above using the find() function is not correct.
ReplyDeleteInstead, if you already have a reference to a radio button group, for example:
var myRadio = $('input[name=myRadio]');
Use the filter() function, not find(). (find() is for locating child elements, whereas filter() searches top-level elements in your selection.)
var checkedValue = myRadio.filter(':checked').val();
You can use the :checked selector along with the radio selector.
ReplyDelete$("form:radio:checked").val();
This should work:
ReplyDelete$("input[name='radioName']:checked").val()
Note the "" usaged around the input:checked and not '' like the Peter J's solution
Another option is:
ReplyDelete$('input[name=radioName]:radio:checked').val()
In a JSF generated radio button (using <h:selectOneRadio> tag), you can do this:
ReplyDeleteradiobuttonvalue = jQuery("input[name='form_id\:radiobutton_id']:checked").val();
where selectOneRadio ID is radiobutton_id and form ID is form_id.
Be sure to use name instead id, as indicated, because jQuery uses this attribute (name is generated automatically by JSF resembling control ID).
Get all radios:
ReplyDeletevar radios = jQuery("input[type='radio']");
Filter to get the one thats checked
radios.filter(":checked")
$("input:radio:checked").val();
ReplyDeleteAlso, check if the user does not select anything.
ReplyDeletevar radioanswer = 'none';
if ($('input[name=myRadio]:checked').val() != null) {
radioanswer = $('input[name=myRadio]:checked').val();
}