Reputation: 609
I've been trying to code a function that goes to a different page when the user hits the enter key into a certain input box. Here's the code:
<div class="container">
<div class="row">
<form>
<div id="search" onkeypress="enter(event)" >
<div class="input-group col-md-offset-8 col-md-3">
<input type="text" class="form-control">
<div class="input-group-btn">
<a href="mylink.com" tab-index="-1" class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></a>
</div>
</div>
</div>
</form>
</div>
</div>
<script>
function enter(event){
if (event.keyCode == 13){
document.location.href = "newpage.com";
}
}
</script>
Thanks in advance!
Upvotes: 1
Views: 1049
Reputation: 129
What's happening is simple, you have a "form" tag, so when you hit enter, "onkeypress" is firing the event and the function "enter" that you created is handling that event, but having a "form" tag it just submitting a form.
To avoid that, just remove the "form" tag or just replace it for the following:
<form onsubmit="event.preventDefault();">
Also, you have to add the protocol if you want to redirect to a different page, like:
document.location.href = "http://newpage.com";
I hope it helps :)
Upvotes: 1