Sakvad Sakvad - 1 year ago 55
Javascript Question

JavaScript Refreshes Instead of Changing Pages

I am unable to figure out why my page will not redirect to the set page. Whenever the condition is met, the page simply refreshes. I have gone into the browser console and pasted my redirect code, and it does redirect.

Full JavaScript Function:

function formSubmit(){
var formFN = document.getElementById("fName");
var formLN = document.getElementById("lName");

if( formFN.value.length == 0 || formFN.value == null){
window.alert("Please enter your first name.");
return false;
}
else if( formLN.value.length == 0 || formLN.value == null){
window.alert("Please enter your last name.");
return false;
}
else
{
document.location = "resultPage.html";
return false;
}
}


HTML Part:

<div id="form">
<form action="">
<h3>Thanks for visiting!</h3>
<label for="fName">First Name:</label>
<input type="text" id="fName" value="">
<br>
<label for="lName">Last Name:</label>
<input type="text" id="lName" value="">
<br>
<button onclick="formSubmit();">
Submit
</button>
<!-- <input type="submit" value="Submit" onclick="formSubmit();"> -->
</form>
</div>

Answer Source

By default, button elements have a type attribute of submit. Based on your question, you probably want this instead:

<button type="button" onclick="formSubmit();">
     Submit
</button>

If you want a more general solution, you'd be better off capturing and handling the submit event on the form since things like pressing return in an input would trigger a submit as well.

window.addEventListener("load", function() {
    document.getElementById("form").getElementsByTagName("form")[0].addEventListener("submit",function(event) {
        event.preventDefault(); // Stop the normal action for this event

        var formFN = document.getElementById("fName");
        var formLN = document.getElementById("lName");

        if( formFN.value == null || formFN.value.length == 0 ){
            alert("Please enter your first name.");
        }
        else if( formLN.value == null || formLN.value.length == 0 ){
            alert("Please enter your last name.");
        }
        else {
            document.location = "resultPage.html";
        }
    });
});
<div id="form">
    <form>
    <h3>Thanks for visiting!</h3>
        <label for="fName">First Name:</label>
        <input type="text" id="fName" value="">
        <br>
        <label for="lName">Last Name:</label>
        <input type="text" id="lName" value="">
        <br>
        <button>Submit</button>
    </form>
</div>

Edit: It occurs to me that you should check for nulls before checking for length. (If .value is null then checking .value.length will throw an error.) Adjusted code accordingly.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download