I have seen the jquery documents, stackoverflow and other forums, but this doesn’t seem to work.
I have a radio button in a form, and I want to get the value of the selection.
If I remove the radio button from the form, I can get it by simply
var first_val = $('input:radio[name=Question0]:checked').val();
But if I add it to to a form name=lifestyle
Any of these combinations don’t work
I have a form named lifestyle
I have tried all the options in Chrome and it doesn’t seem to work
Option 1
var first_val = $('#lifestyle input:radio[name=Question0]:checked').val();
alert($('#lifestyle input:radio[name=Question0]:checked').val());
Option 2
var first_val = $('form input:radio[name=Question0]:checked').val();
alert($('form input:radio[name=Question0]:checked').val());
Option 3
var first_val = $('#lifestyle input:radio[name=Question0]:checked', '#lifestyle').val();
alert($('#lifestyle input:radio[name=Question0]:checked','#lifestyle').val());
And so on..
I don’t get the value and the alert says undefined.
“If I remove the radio button from the form, I can get it by simply”
That selector should work regardless of whether the input belongs to a form or not. You’d only need to specify the form if there are multiple forms which each have inputs with the same name.
I would expect this to work:
Option 1 doesn’t work because your form has the name “lifestyle” but you are trying to use the id selector format with a “#”. So:
Option 2 looks fine to me, assuming you have only one form element on the page.
Option 3 has the same problem with “#” selecting by id rather than name, but also by using the
$("selector", context)syntax you are supposed to supply “A DOM Element, Document, or jQuery to use as context” (as explained here, not a string, but in any case providing an element as context and then looking for that element within itself doesn’t make sense.