Hi javascripters..
I have been trying to use some javascript to validate a form before submitting it to a servlet:ResrvChk2 from a jsp:ResrvChkGui.jsp
<form action='ResrvChk2' method='Post'>...
<p><input type='submit' value='Submit' name='subButton'
onClick="tstInput(this.form)"></p>
</form>
My tstInput fuction is shown below
function tstInput(form) {
var bDate = false; var bNN = false;
// chk if startDate in year 2000 and XX-MON-YYYY format
bDate = chkDate(form);
// chk if numNights NOT negative NOT>20
bNN = chkNN(form);
if(bDate & bNN)
{ alert("input fields OK, will submit");
document.form1.submit();
}
else
{alert("input fields BAD, will not submit");}
}
The function (and related functions) work ok and alerts appear correctly indicating when I put in bad or good input. The problem is that the page always submits.. and I only want it to submit if the input is good.
Any ideas?
Danne
12-02-2004, 01:02 PM
Call the validation function on the "onsubmit" event instead, and have it return false, if something went wrong.
The function:
function tstInput(form) {
...
if(!bDate || !bNN){
alert("input fields BAD, will not submit");
return false;
}
return true;
}
The form:
<form ... onsubmit="return tstInput(this)">
verobel
12-02-2004, 02:53 PM
I tryed your suggestion and at first it did not work. Then I deleted all files in InternetExplorer and retryed and it worked fine.
Is onClick no longer used for submitting forms?
Thanks alot, John :thumbsup: