Friday, November 16, 2007
Stopping form from submitting
Let's assume you have a form on a web page. It has an textarea and a form submit button. You want to alert the user that the textarea is required before submitting the form. You don't want the form to submit if validation fails, otherwise submit the form as normal.
Here is the sample of how to handle this. NOTE: This works for ASP.Net also. Besure to include the return keyword in the onclick of the button.
<html>
...
<body>
<form ... >
function validate()
{
var myTextArea = document.getElementById('MyTextArea');
var val = myTextArea.value;
if (val == "")
{
alert("The text area is required. Please enter text and try again.");
return false;
}
else
{
return true;
}
}
<textarea id="MyTextArea" id="MyTextArea" cols="20" rows="2"></textarea>
<input id="Submit1" type="submit" value="submit" onclick="return validate();"/>
</form>
</html>
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment