-3

How can I check which of the two radio button is checked in javascript/jquery in order to get the value of the input considering the fact that, in the HTML, both of them are by default unchecked (no checked attribute is added)

<input type="radio" name="AS88" value="true" required>
<input type="radio" name="AS88" value="false">

The following code does not work:

var elements = document.getElementsByName("AS88");
for (var i=0, len=elements.length; i<len; ++i) {
    if (elements[i].checked) {
        alert(elements[i].value)
    } 
};

EDIT:

Solutions with :checked in jquery such as:

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

always return undefined

5
  • you have to capture it on change() event of the radio button. Commented Dec 30, 2013 at 15:20
  • Sounds like a timing issue. Are you sure you're not executing the code before those inputs exist? Commented Dec 30, 2013 at 15:24
  • the code is executed just before the submit so all the input already exist Commented Dec 30, 2013 at 15:27
  • You say "both of them are by default unchecked", so unless the user actually clicks one of them both will remain in the unchecked state and your code (with or without jQuery) will not find a checked one. Commented Dec 30, 2013 at 15:31
  • I use required so the user is forced to select the option before the submit... Commented Dec 30, 2013 at 15:37

1 Answer 1

7

use attribute selector along with :checked selector and .val() to get the value of the checked input element with name AS88

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

Demo: Fiddle

Sign up to request clarification or add additional context in comments.

8 Comments

This always returns undefined
@GigiGammino if none of the radios are checked then it will return undefined
@GigiGammino check the attached jsfiddle
it works fine on fiddle but the same code (except for the click function) returns undefined for me!
that means the selector $('input[name="AS88"]:checked') is wrong
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.