Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect on form's submission with window.location.href

Tags:

html

forms

Trying out this simple code, I am amazed it didn't work, here we go :

<form method="get" action="" >
    <input type="submit" value="validate" onclick="redirect(); alertIt(); "/>
</form>
<script>
    function redirect(){
       window.location.href = "test.html" ;
    }
</script>
<script>
function alertIt(){
   alert("redirect");
}
</script>

The code is just supposed to redirect to "test.html" on click of the submit button, which it fails to do. On the other hand : alertIt() works fine... My question is the following : does event handeling into a form have some special rules I should know about ?

like image 955
Akheloes Avatar asked May 21 '13 21:05

Akheloes


2 Answers

You need to return false if you want the form not to submit anyway.

function redirect(){
       window.location.href = "test.html" ;
}

Should be

function redirect(){
    window.location.href = "test.html" ;
    return false;
}

You should also hook on the submit event and not the click event preferably, and return in the handler.

onclick="return redirect(); alertIt(); " 

Would work (but not alert)

Optimally, what you'd want to do is add an id to the form for example myForm and attach an event to it.

document.getElementById("myForm").addEventListener("submit",function(){
    alertIt();
    return redirect(); 
},false);
like image 158
Benjamin Gruenbaum Avatar answered Oct 30 '22 05:10

Benjamin Gruenbaum


You can use location.replace() too. Following link explains JavaScript location with working example.

http://www.codecandle.com/Articles/450/Javascript/Browser-Objects/Javascript-Location/codedetail.aspx

may help you.

like image 35
Josefh luis Avatar answered Oct 30 '22 04:10

Josefh luis