-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

GiGamma
  • 894
  • 1
  • 9
  • 16
  • you have to capture it on `change()` event of the radio button. – Venkata Krishna Dec 30 '13 at 15:20
  • Sounds like a timing issue. Are you sure you're not executing the code before those inputs exist? – Teemu Dec 30 '13 at 15:24
  • the code is executed just before the submit so all the input already exist – GiGamma Dec 30 '13 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 Dec 30 '13 at 15:31
  • I use **required** so the user is forced to select the option before the submit... – GiGamma Dec 30 '13 at 15:37

1 Answers1

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

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531