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 ?
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With