Question

My code:

var isSomethingChecked = (document.getElementByName("koalaCheck").checked ||
                          document.getElementByName("kangarooCheck").checked);

Why does this code throw an exception called "Type Error"?

Was it helpful?

Solution

There is no function called getElementByName. what you need is getElementsByName which returns an array of all of the elements that have that name. so you can use:

var isSomethingChecked = (document.getElementsByName("koalaCheck")[0].checked ||    
                         document.getElementsByName("kangarooCheck")[0].checked);

OTHER TIPS

That would be because the correct method is document.getElementsByName(). You missed an s.

View the documentation.

Assuming you do not wish to check each checked state per element(as this method returns an array).. I would use document.getElementById().. but that is without seeing your html.

getElementsByName returns an array of all elements with the given name. You either need to use the getElementById function or specify a particular element in the returned array like so:

var isSomethingChecked = (document.getElementsByName("koalaCheck")[0].checked || document.getElementsByName("kangarooCheck")[0].checked);

You get the "Type Error" because you are checking whether an array is checked instead of a particular element.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top