简体   繁体   中英

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>

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.

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

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

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>
onsubmit="function(){validate('theform');return false};"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM