This is kind of confusing, but I'll try to explain it as well as I can. I have 4 select
menus laid directly on top of each other with absolute
positioning. At any one time, three of them are invisible (with display: none;
) while 1 of them is visible (with display: inline;
). I have a JavaScript code that detects which one is visible, and then it's supposed to get the value of an input
field, append it on the value of the visible select
, and go to that URL.
Here is the basic idea in code:
<form onsubmit="goTo()">
<input type="text" id="query" value="" />
<select class="service">
<option value="https://www.google.com/search?q=" selected>Web</option>
<option value="https://www.google.com/search?tbm=isch&q=">Images</option>
<option value="https://www.google.com/maps?q=">Maps</option>
</select>
<select class="service">
<option value="http://search.yahoo.com/search?p=" selected>Web</option>
<option value="http://search.yahoo.com/search/images?p=">Images</option>
<option value="http://search.yahoo.com/search/video?p=">Videos</option>
</select>
<select class="service">
<option value="http://www.bing.com/?q=" selected>Web</option>
<option value="http://www.bing.com/images/?q=">Images</option>
<option value="http://www.bing.com/videos/?q=">Videos</option>
</select>
<select class="service">
<option value="http://www.dogpile.com/info.dogpl.t6.2/search/web?q=" selected>Web</option>
<option value="http://www.dogpile.com/info.dogpl.t6.2/search/images?q=Greeny">Images</option>
<option value="http://www.dogpile.com/info.dogpl.t6.2/search/video?q=">Videos</option>
<select>
<button type="submit">Search</button>
And the JavaScript (there is way more code than this, but I'll only include the relevant part:
function goTo() {
var value
var elements = document.getElementsByClassName('service');
for (var i = 0; i < elements.length; i++) {
if(elements[i].style.display === 'inline') {
value = elements[i].value;
window.location.href = value + document.getElementById("query").value;
break;
}
}
}
My problem is that all that happens when I click submit is the page reloads.
You need to stop the default action of the "submit" event, which is to reload the page.
Change the form tag to:
<form onsubmit='goTo(); return false'>
You could alternatively do this by explicitly preventing the default action by manipulating the event object, but I think returning false
from the handler is pretty universal.