Preventing Form Submission


<form onsubmit="return checkform(this);"> 

There are some good reasons to hinder the browser from submitting the form, for instance, when some required fields have not been filled out yet. To do so, false must be returned in the handling code for the form's submit event:

<form onsubmit="return false;"> 


Of course, the code should usually decide based on the form data whether the form should be allowed to submit. Therefore, a custom function usually takes care of that and, at the end, returns true or false.

The following form can be submitted only if there is a value in the text field:

The Form Can Be Submitted Only When the Text Field Is Filled Out (nosubmit.html)

<script language="JavaScript"   type="text/javascript"> function checkform(f) {   if (f.elements["textfield"].value == "") {     return false;   } else {     return true;   } } </script> <form onsubmit="return checkform(this);">   Username <input type="text" name="textfield" />   <input type="submit" value="Submit data" /> </form> 

Once again, this works only with JavaScript activatedone more reason to validate all data on the server side!




JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net