Skip to content
Advertisement

Why does this form validation for empty input values fail?

In my code there is a radio button group called fitness which has six options and they have values from 1 to 6. I have written a function to check whether the user has selected one of the above options:

JavaScript
JavaScript

This is my <form>:

JavaScript

But it submits even if the user has not selected an option. Can someone tell me the reason for this?

Advertisement

Answer

if(document.getElementById(“fitness”).value==null)

Having multiple elements with the same ID is invalid. getElementById will return one of them (first? last? depending on browser), not all of them.

Since all of them have a value, the above expression will always return false.

Anyhow, in order to be successful (be submitted with the form), form controls must have a name, so just remove all the IDs (they don’t do anything useful).

Also, having a control with a name of submit replaces the form’s submit method, so if you attempt:

JavaScript

you’ll get an error as you’re trying to call the element named submit, not the method. So don’t give a control a name of “submit”.

So the function can be:

JavaScript

That will loop over all the controls with a name of “fitness” and return false if none of them are checked, or undefined if one is checked (so the form will submit).

The above will work in any browser that supports javascript.

Edit

As @Quasimodo’s clone suggests, the loop can be simplified to return if a checked radio button is found and do the error thing otherwise:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement