Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use an input field as query parameter to a destination?

For my sample Google Chrome extension, I have a textbox and a link:

<input id="textbox" type="text" value="" size="25" />
<a class="button" href="http://www.google.com"><span>Search</span></a>

When the user clicks on the link, I want the browser to actually go to:

http://www.google.com/search?q=<whatever was in textbox>

How can I do this?

like image 468
Lazer Avatar asked Jan 22 '26 03:01

Lazer


1 Answers

I strongly advice you to use an ordinary form with a submit button for this. In that case, you even don't have to use JavaScript at all. For example:

<form action="http://www.google.com/search">
    <input id="textbox" name="q" type="text" value="" size="25" />
    <input type="submit" value="Search" />
</form>

If you really want to use the provided markup, best thing you can do is to add an ID to the a element, e.g. searchButton, and then do:

document.getElementById("searchButton").onclick = doSearch;

function doSearch() {
    var v = document.getElementById("textbox").value;
    window.location = "http://www.google.com/search?q=" + encodeURIComponent(v);
    return false; // not entirely necessary, but just in case
}
like image 165
Marcel Korpel Avatar answered Jan 24 '26 18:01

Marcel Korpel