Intelwalk
Intelwalk

Reputation: 671

Javascript to check for form data does not work

I have the following code to check for form data and I can't figure out why its not working.

<script type="text/javascript">
            function checkStuff() {
                // By default, we plan to submit the form.
                var formOkay = 1;

                // Check to see if field_1 has a value.  If not, we note that by changing our variable.
                if(document.getElementById('requestorfirstname').value == '')
                    formOkay = 0;

                // Let the user know something is wrong somehow.  An alert is easiest.
                alert('Requestor Name Required!');

                // If you return true the form will submit.  If you return false it will not.
                if(formOkay == 1) {
                    return true;
                } else {
                    return false;
                }
            }
        </script>

Now here is the html form piece its checking onsubmit.

<input type="text" name="requestorfirstname" />

Thanks for the help!

Upvotes: 0

Views: 104

Answers (3)

Marc B
Marc B

Reputation: 360592

A name attribute on an HTML element is NOT the same as an id. You have no id on your input field, so there's no way for getElementById to find it. Change the element to:

<input type="text" name="requestorfirstname" id="requestorfirstname" />
                                            ^^^^^^^^^^^^^^^^^^^^^^^^ - add this

Upvotes: 2

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114347

document.getElementById looks for elements by ID. Your field doesn't have an ID, it has a NAME.

Upvotes: 4

Rob W
Rob W

Reputation: 348972

document.getElementById selects an element by id, not by name.

Some ways to solve the problem:

Upvotes: 2

Related Questions