I’m having some strange problem with my JS program. I had this working properly but for some reason it’s no longer working. I just want to find the value of the radio button (which one is selected) and return it to a variable. For some reason it keeps returning undefined
.
Here is my code:
function findSelection(field) {
var test = 'document.theForm.' + field;
var sizes = test;
alert(sizes);
for (i=0; i < sizes.length; i++) {
if (sizes[i].checked==true) {
alert(sizes[i].value + ' you got a value');
return sizes[i].value;
}
}
}
submitForm
:
function submitForm() {
var genderS = findSelection("genderS");
alert(genderS);
}
HTML:
<form action="#n" name="theForm">
<label for="gender">Gender: </label>
<input type="radio" name="genderS" value="1" checked> Male
<input type="radio" name="genderS" value="0" > Female<br><br>
<a href="javascript: submitForm()">Search</A>
</form>
Since jQuery 1.8, the correct syntax for the query is
Not
$('input[@name="genderS"]:checked').val();
anymore, which was working in jQuery 1.7 (with the @).This is pure JavaScript, based on the answer by @Fontas but with safety code to return an empty string (and avoid a
TypeError
) if there isn't a selected radio button:The code breaks down like this:
<input>
type, (b) has aname
attribute ofgenderS
, and (c) is checked.genderSRadio
variable is truthy if Line 1 finds the control and null/falsey if it doesn't.For JQuery, use @jbabey's answer, and note that if there isn't a selected radio button it will return
undefined
.lets suppose you need to place different rows of radio buttons in a form, each with separate attribute names ('option1','option2' etc) but the same class name. Perhaps you need them in multiple rows where they will each submit a value based on a scale of 1 to 5 pertaining to a question. you can write your javascript like so:
I would also insert the final output into a hidden form element to be submitted together with the form.
In case someone was looking for an answer and landed here like me, from Chrome 34 and Firefox 33 you can do the following:
or simpler:
refrence: https://developer.mozilla.org/en-US/docs/Web/API/RadioNodeList/value