james
james

Reputation: 73

JS script not working else if with redirect

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.

Upvotes: 0

Views: 139

Answers (2)

Claude
Claude

Reputation: 11

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;
}

Upvotes: 0

epascarello
epascarello

Reputation: 207511

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.

Upvotes: 4

Related Questions