user487743
user487743

Reputation: 2235

Javascript Forms

I something weird going on with my javascript code. I have a very very simple form that returns a javascript function called validate. Basically the function checks to see if the box is empty, if it is, it marks the box yellow.

My problem is, when I click the button with nothing in the box, it just refreshed the page and brings me to the top of the page. I have put alerts in the function and it actually changes the color of the box, but after I click ok on the alert, the page refreshes. Here is the code I have.

Here is the form in the body of the HTML:

<form id="theform" method="post" action="" onsubmit="return validate('theform');">


<input type="text" name="food" value="" style="width: 160px" />


 <input type="submit" value="submit" />

   </form>

and Here is the javascript that is in the Head of the HTML:

 <script type="text/javascript">
    function validate(formName) {

        var theform = document.getElementById(formName);


     if (theform.food.value == "") {

            theform.food.style.background = "yellow";

        }
    }

    </script>

Upvotes: 0

Views: 172

Answers (4)

Falcon
Falcon

Reputation: 1463

onsubmit="function(){validate('theform');return false};"

Upvotes: 0

Marko
Marko

Reputation: 72230

If the validation fails you need to return false so that the form doesn't get submitted.

<script type="text/javascript">
    function validate(formName) {
        var theform = document.getElementById(formName);
        if (theform.food.value == "") {
            theform.food.style.background = "yellow";
            return false;
        }
    }
</script>

Upvotes: 0

Eli
Eli

Reputation: 17825

Since your function runs onsubmit, when the function is finished it will submit. You don't have an action defined on your form, so it just reloads the page. If you wish for the form to not submit, just return false at the end of your function.

Upvotes: 1

sdleihssirhc
sdleihssirhc

Reputation: 42496

You need to explicitly return false for the submit action to be canceled.

(Only if food.value is empty, of course.)

Upvotes: 0

Related Questions