Coder Perfect

How do I retrieve the value of the selected radio button?

Problem

With my JS software, I’m having an odd difficulty. This used to function fine, but for some reason it no longer does. I simply want to return the value of the radio button (which one is picked) to a variable. It continues returning undefined for some reason.

My code is as follows:

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>

Asked by mkyong

Solution #1

This method works with any browser.

document.querySelector('input[name="genderS"]:checked').value;

This is a straightforward method for obtaining the value of any input type. You also don’t have to use jQuery.

Answered by Giorgos Tsakonas

Solution #2

This is an example of what you could do:

jsfiddle

Thank you for your edit recommendations, HATCHA and jpsetung.

Answered by jbabey

Solution #3

document.forms.your-form-name.elements.radio-button-name.value

Answered by imran ansari

Solution #4

The correct syntax for the query has been since jQuery 1.8.

$('input[name="genderS"]:checked').val();

$(‘input[@name=”genderS”]:checked’) is not true. val(); no longer works, as it did in jQuery 1.7 (with the @).

Answered by jptsetung

Solution #5

let genderS = Array.from(document.getElementsByName("genderS")).find(r => r.checked).value;

Answered by Nappy

Post is based on https://stackoverflow.com/questions/9618504/how-to-get-the-selected-radio-button-s-value