javascript - How do I stop JSP page from executing the servlet? -
this question has answer here:
i trying make simple web app. should take inputs, validate them , store in database or display error. i'm having problem while validating form through external javascript. if field empty, checking done jsp directs control servlet. need stop jsp page further going forward. please help! here code:
jsp:
<%@ page language="java" contenttype="text/html; charset=iso-8859-1" pageencoding="iso-8859-1"%> <!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1"> <title>welcome</title> <script type="text/javascript" src="js/validationjs.js"></script> </head> <body> <h1 align="center">teacher management system</h1> <form name="teacherregistrationform" action="teachercontroller" method="post" > <input type="hidden" name="source" value="addteacher"> <table> <tr> <td> id:<input type="text" name="teacherid" /> </td> </tr> <tr> <td> name:<input type="text" name="teachername" /> </td> </tr> <tr> <td> address:<textarea type="text" rows="5" name="teacheraddress" ></textarea> </td> </tr> <tr> <td> qualification:<input type="text" name="teacherqualification" /> </td> </tr> <tr> <td> years of experience:<input type="text" name="teacherexp" /> </td> </tr> <tr> <td> age:<input type="text" name="teacherage" /> </td> </tr> <tr> <td> <input type="submit" name="teacheradd" value="add" onclick="validate()"/> <input type="reset" name="teacherreset" value="reset fields" /><br><br> <a href="welcomepage.jsp" style="text-decoration: underline">go back</a> </td> </tr> </table> </form> </body> </html>
javascript:
function validate() { boolean result=false; if(document.teacherregistrationform.teacherid.value=="") { document.teacherregistrationform.teacherid.value= "please enter valid id"; document.teacherregistrationform.teacherid.focus(); alert("please enter valid id"); result=false; }else{result=true;} return result; }
you need use <input type="button"
you need change <input type="submit" name="teacheradd" value="add" onclick="validate()"/>
shown below:
<input type="button" name="teacheradd" value="add" onclick="validate()"/>
<input type="submit"
submits form servlet, rather use <input type="button"
, call validate()
(you doing this) validate inputs , once inputs valid, can use document.myform.submit()
submit form
.
you can refer below updated java script validate()
method:
function validate() { if(document.teacherregistrationform.teacherid.value=="") { document.teacherregistrationform.teacherid.value= "please enter valid id"; document.teacherregistrationform.teacherid.focus(); alert("please enter valid id"); return; } else{ document.teacherregistrationform.submit(); } }
Comments
Post a Comment