0

I have the code below its just a simple validator script/code that checks if field is empty it throws an error message and redirect if not. Somehow it's not working im just a beginner to this though. The validation works but when redirecting its not.

<body>
<div class="mail">
<h2>Input your Name and Submit</h2>
<form name="form1" onsubmit="required()">
<ul>
<li><input type='text' name ='text1'/></li>
<li class="rq">*Required Field</li>
<li><input type="submit" name="submit" value="Submit" /></li>
</ul>
</form>
</div>
<script src="non-empty.js"></script>
</body>

Javascript:

function required()
{
var empt = document.form1.text1.value;
if (empt === "")
{
alert("Please input a Value");
return false;
}
else 
{
window.location.href = '../continue.php';
return true; 
}
}

The checking if empty works but the redirection if not empty is not working.

james
  • 73
  • 1
  • 9
  • what happens when the redirection doesn't work? – jonathanGB Oct 11 '16 at 02:48
  • You are submitting a form and you are setting the location. Pick one or the other. If you want to change the page, than just set the action of the form. – epascarello Oct 11 '16 at 02:49
  • `window.location.href = '../continue.php';` this line has no problem. Make sure that PHP page is really doing stuff, because if you change the page to e.g. Google, it works. – Daniel Cheung Oct 11 '16 at 02:53
  • http://stackoverflow.com/questions/3350247/how-to-prevent-form-from-being-submitted onsubmit="return require()" – dcochran Oct 11 '16 at 02:53

2 Answers2

4

Okay so you have a couple of issues. One you are trying to cancel the form submission, but you lack a return statement in the onsubmit handler.

<form name="form1" onsubmit="return required()">

Next issue is you have a form that is trying to submit back to itself and you are setting the location. So you have two actions that have a race condition where one will win. So you got to pick one. Either you submit the form, or you change the location. Now the form can change the location if you set the action attribute.

<form name="form1" onsubmit="return required()" action="NewPage.html">

and the script:

function required() {
    var empt = document.form1.text1.value;
    if (empt === "") {
        alert("Please input a Value");
        return false;
    }
    return true;
}

or return false in the else and set the location like you were.

epascarello
  • 204,599
  • 20
  • 195
  • 236
0

You could do this :

<form name="form1" onsubmit="return required()" >
<ul>
<li><input type='text' name ='text1'/></li>
<li class="rq">*Required Field</li>
<li><input type="submit" name="submit" value="Submit" /></li>
</ul>
</form>

and then :

else 
{
  window.location.replace('../continue.php');
  return false;
}
Claude
  • 11
  • 5