I am implementing a form in html and check empty text boxes on onSubm开发者_开发技巧it
event of form. In my JavaScript code I returns false but the form is still submit and redirect to new URL.
What goes wrong in this code?
function checkBlank(form)
{
var returnvar=true;
if(form.driver.value=="")
{
alert("You can't left text box Driver as blank.. ");
driver.focus();
returnvar=false;
}
return returnvar
}
<form name="form1" action="/Assignment6/DataBaseServlet" onSubmit="return checkBlank(form1);" method="post">
You changed your variable names
returnvar
returnval
and the onsubmit line
return checkBlank(form1);
should use this
and not form1
return checkBlank(this);
Also driver
is not defined.
driver.focus();
It should be referenced with the form
form.driver.focus();
Your entire function can be:
function checkBlank(form) {
return form.driver.value == "";
}
If you the message isn't required. Or perhaps:
function checkBlank(form) {
if (!form.driver.value) {
alert("Please enter a value in the driver field");
return false;
}
}
But you may want slightly more robust validation as that will allow a string of one or more spaces.
Hi its because of action tag .
I just change my code lke this and it's working fine.enter code here
function checkBlank(form)
{
var returnval=true;
form.action="/Assignment_8/";
if(form.driver.value=="")
{
alert("You can't left text box Driver as blank ");
driver.focus();
returnval= false;
}
if(form.url.value=="")
{
alert("You can't left text box url as blank ");
form.url.focus();
returnval= false;
}
if(form.username.value=="")
{
alert("You can't left text box username as blank ");
form.username.focus();
returnval= false;
}
if(form.password.value=="")
{
alert("You can't left text box password as blank ");
form.password.focus();
returnval= false;
}
if(form.query.value=="")
{
alert("You can't left text box query as blank ");
form.query.focus();
returnval= false;
}
if(returnval){
form.action="/Assignment_8/database.jsp";
}
return true;
}
//and form tag is..
<form name=form1 method="post" onsubmit="return checkBlank(form1)">
精彩评论