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=""><span>Search</span></a>
When the user clicks on the link, I want the browser to actually go to:
=<whatever was in textbox>
How can I do this?
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."><span>Search</span></a>
When the user clicks on the link, I want the browser to actually go to:
http://www.google./search?q=<whatever was in textbox>
How can I do this?
Share Improve this question edited May 31, 2011 at 20:11 Lazer asked May 31, 2011 at 19:26 LazerLazer 95.1k115 gold badges290 silver badges368 bronze badges 2- Added google-chrome tags again, any suggestions specific to Chrome are also wele.. – Lazer Commented May 31, 2011 at 20:12
- How is the substance of your question or the proposed solutions dependent upon Chrome? – BryanH Commented May 31, 2011 at 20:45
4 Answers
Reset to default 3I 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./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./search?q=" + encodeURIComponent(v);
return false; // not entirely necessary, but just in case
}
UPDATED SOLUTION:
Here's an example with inline javascript that sets the href of the link appropriately and then lets normal processing handle the redirect (added encodeURIComponent base on Marcel's ment).
<input id="textbox" type="text" value="" size="25" />
<a class="button" id="googleLink" href="willBeChanged"
onclick="this.href='http://www.google./search?q=' + encodeURIComponent(document.getElementById('textbox').value);">
<span>Search</span>
</a>
Use JQuery to make your life easy.
Your JQuery would look like this:
$("#linky").attr('href',"http://www.google./search?q="+$("#textbox").val());
Your HTML would look like this:
<input id="textbox" type="text" value="" size="25"></input>
<a class="button" href="www.google." id="linky"><span>Search</span></a>
Using jquery:
<script type="text/javascript">
$(document).ready(function(){
$("#textbox").keyup(function () {
var searchstring = $(this).val();
searchstring = encodeURIComponent(searchstring);
$('#searchlink').attr('href', 'http://www.google./search?q=' + searchstring);
});
});
HTML markup:
<input id="textbox" type="text" size="25">
<a class="button" href="http://www.google." id='searchlink'>Search</a>