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:
<f开发者_开发百科orm 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.
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>
You need to explicitly return false for the submit action to be canceled.
(Only if food.value
is empty, of course.)
onsubmit="function(){validate('theform');return false};"
精彩评论