0

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!

0

3 Answers 3

4

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

4
  • That was it! After I fixed it the form still completed, what do I need to change to go back to the form instead of continuing? Thanks
    – Intelwalk
    Feb 21, 2012 at 15:37
  • 1
    It all depends on how you are calling this function. Feb 21, 2012 at 15:46
  • I'm calling it onsubmit when the button is pressed.
    – Intelwalk
    Feb 21, 2012 at 16:00
  • 1
    Use a regular button. Use onclick to call your function, then submit the form if it passes validation. Feb 21, 2012 at 16:06
2

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

Some ways to solve the problem:

0
2

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

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.