David G
David G

Reputation: 96790

How do I check if either radio button with the same name is selected?

I have two radio buttons with the same name. Using JavaScript, how can I check to see if either button is in focus? Here is what I've done so far; it's part of my form validation:

if (element.type == "radio") {
    if (element.checked === true) break;
    else error.push(element.name || element.id);
}

And if the array "error" has any content in it, I'll know that a check box is not selected. But it will say "form validated" only if both radios are selected. But I only want to know if either one with the same name is selected. How do I do that?

Upvotes: 1

Views: 276

Answers (2)

kjetilh
kjetilh

Reputation: 4976

This is how you could do it with jQuery:

$('input[name=test]').each(function() {
    if (this.checked) alert('yep');
})

Upvotes: 0

Stefan Kendall
Stefan Kendall

Reputation: 67802

It's a radio button. Set one to be selected by default, and having both be unchecked will be impossible and won't need validation.

Upvotes: 2

Related Questions