Validate form input using the onsubmit
event attribute.
Things to note:
onsubmit
attribute to set handler for "submit" eventfalse
stops the form submissionthis
refers to the instance of the object (the form)<form onsubmit="return Validate(this)" method="get" action="http://cscie12.dce.harvard.edu/echo">
<div><label for="YourName1">Enter your name</label>:
<input type="text" id="YourName1" name="YourName"/><br/>
<input type="submit" value="Submit Information"/></div>
</form>
In
script
element within head
element (<script type="text/javascript">
):
function Validate(myForm) {
console.log(myForm);
if(myForm.YourName.value == null || myForm.YourName.value == "") {
console.log("in failure branch");
alert("Please enter your name!");
myForm.YourName.focus();
myForm.YourName.style.backgroundColor = '#ff3';
return false;
} else {
console.log("in success branch");
return true;
}
}
Copyright © David Heitmeyer