Reputation: 517
I have a textbox and a search button.
Onclicking
search button the window.location
is working.
But on pressing enter key window.location
is not working.
I have read that submit works when enter key is pressed but why here on pressing enter key window.location is not working.
Here is my code:
<div>
<form id="form">
<input id="bar"
style="height:26px; left:29%; top:270px; position:absolute;
border:1px solid #CCC;
font:20px arial,sans-serif;
background-color:transparent; z-index:6; outline:none;
width:500px;"
spellcheck="true";
onfocus="";
type="text" value="" title="Search" autocomplete="on" maxlength="2048" />
</form>
<input id="searchbutton"
style="height:30px; top:330px; position:absolute; left:33%; background-image:-webkit-linear-gradient(top,#f8f8f8,#f1f1f1);
-webkit-box-shadow:0 1px 1px rgba(0,0,0,0.1);
background-color:#f8f8f8;
border:1px solid #c6c6c6;
box-shadow:0 1px 1px rgba(0,0,0,0.1);
color:#333;
border-radius:2px;"
type="button" value="Google Search"/>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function() {
$("#searchbutton").click(function() {
var q;
q = $("#bar").val();
window.location = "https://www.google.com/search?q=" + q;
});
$('#form').submit(function() {
var q;
q = $("#bar").val();
window.location = "https://www.google.com/search?q=" + q;
});
});
</script>
Upvotes: 1
Views: 3845
Reputation: 1957
You need to cancel the form submit. Try changing the code to as follows:
<script>
$(document).ready(function(){
$("#searchbutton").click(function(){
var q;
q=$("#bar").val();
window.location = "https://www.google.com/search?q="+q;
});
$('#form').submit(function(){
var q;
q=$("#bar").val();
window.location = "https://www.google.com/search?q="+q;
event.preventDefault();
});
});
</script>
UPDATE
When you hit the enter key, the form will initiate the submit event. By default, the page will submit to itself if you don't specify a destination (in the action attribute). Since you are not cancelling the submit event, even though you were trying to redirect the user to a different page, the page submit will take presidence and completes the submit; therefore, the page never redirects to google.com.
Also, as @Quentin mentioned in his comment, it best practice to change:
$("#searchbutton").click(function(){
to
$("#searchbutton").click(function(event){
since the event object is handled differently across different browsers.
Upvotes: 4