softwareplay
softwareplay

Reputation: 1407

Validating radio elements in a form not by the name

I have to validate the radio elements in a form with javascript, but I cannot do it by the name (getElementByName), for reasons that are too long to explain. I'm currently trying to validate it like this:

for (var i=0; i<document.forms[0].elements.length; i++){ 
element = document.forms[0].elements[i];
    if(element.checked){}
            else {alert("whatever");}
}

But in the form there is an element which is a button, and it counts the button when it shouldn't be a part of the radio element validation. This code doesn't validate the form. How do you select only the radio elements of a form? Like type[radio] or something like that?

Thanks in advance for your time. Agnese

Upvotes: 1

Views: 74

Answers (2)

Bilal Murtaza
Bilal Murtaza

Reputation: 795

try this ... updating your code

for (var i=0; i<document.forms[0].elements.length; i++){ 
    element = document.forms[0].elements[i];
    if(element.type == "radio") {
        var isChecked = element.checked;
        alert('radio '+element.id+' is ' + isChecked);
    }
    else { continue; }
}

Upvotes: 1

Claudio Redi
Claudio Redi

Reputation: 68440

You can use type property of the element

if (element.type === 'radio' && element.checked)

Upvotes: 1

Related Questions