0

So I am trying to write javaScript to check my form. I have six radio-type inputs, of which one has to be checked. The radiobuttons are placed in two rows of three radio-inputs. One row has the name 'inschrijving1' and the other three inputs of the other row each has the name 'inschrijving2'. This is the code I used to check the form, but with this code it always returns as false and it always gives an alert.

if(!document.getElementsByName("inschrijving1").checked || !document.getElementsByName("inschrijving2").checked)
{
     alert("Selecteer een dagdeel voor de inschrijving");
     return false;
}

Can anyone see why this is? I only need it to return false and give an alert if none of the six radio-inputs is checked.

1
  • I suspect, getElementsByName returns an array, because it's plural. Commented Oct 21, 2013 at 13:48

1 Answer 1

1

Because getElementsByName() returns a collection/nodeList of elements, which doesn't have a collective checked property. To do this, you'd need to explicitly iterate over each element returned and check them individually.

Assuming you've only got one element of each name:

if(!document.getElementsByName("inschrijving1")[0].checked || !document.getElementsByName("inschrijving2")[0].checked)

Or, in a compliant browser, with more than one of each:

if(!document.querySelector("name=['inschrijving1']:checked") || !document.getElementsByName("name=['inschrijving2']:checked"))

document.querySelector() returns only the first matching (using CSS selector syntax) element that satisfies the supplied selector.

References:

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

4 Comments

Thanks! I see what I did wrong here. But now the whole form-checking-script doesnt work anymore (since this was only a bit of all the checks I did).. The whole form is being checked validate even is everything is left unchecked..
Well, given the lack of any other information whatsoever, I'm not sure how you expect me to help with that?
I'm sorry it was not nice of me to comment that. I'll just try to figure it out myself for now, thanks for your help so far! :)
I'm happy to help (and the problem isn't that you weren't 'nice' (you were perfectly polite), it's just that I can't help unless I can see more of what's going on) if you provide more code, but I susspect that the problem is probably worthy of a separate question (since this particular aspect of the problem seems to have been adequately addressed). :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.