-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?
    – Teemu
    Commented Dec 30, 2013 at 15:24
  • the code is executed just before the submit so all the input already exist
    – GiGamma
    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.
    – nnnnnn
    Commented Dec 30, 2013 at 15:31
  • I use required so the user is forced to select the option before the submit...
    – GiGamma
    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

8
  • This always returns undefined
    – GiGamma
    Commented Dec 30, 2013 at 15:22
  • @GigiGammino if none of the radios are checked then it will return undefined Commented Dec 30, 2013 at 15:23
  • @GigiGammino check the attached jsfiddle Commented Dec 30, 2013 at 15:25
  • it works fine on fiddle but the same code (except for the click function) returns undefined for me!
    – GiGamma
    Commented Dec 30, 2013 at 15:34
  • that means the selector $('input[name="AS88"]:checked') is wrong Commented Dec 30, 2013 at 15:40

Not the answer you're looking for? Browse other questions tagged or ask your own question.