How to use an input field as a request parameter for a destination?

For my example of the Google Chrome extension, I have a text box 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 really go to:

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

How can i do this?

+3
source share
4 answers

I highly recommend you use the regular submit button form for this. In this case, you don’t even need to use JavaScript at all. For instance:

<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, it is best to add an ID to the element a, for example. searchButtonand 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
}
+3
source

UPDATED DECISION:

javascript, href , ( ​​ encodeURIComponent Marcel ).

<input id="textbox" type="text" value="" size="25" />
<a class="button" id="googleLink" href="willBeChanged" 
 onclick="this.href='http://www.google.com/search?q=' + encodeURIComponent(document.getElementById('textbox').value);">
  <span>Search</span>
</a>
+1

Use jQuery to make your life easy.

Your jQuery will look like this:

$("#linky").attr('href',"http://www.google.com/search?q="+$("#textbox").val());

Your HTML will look like this:

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

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.com/search?q=' + searchstring);
  });

   });

HTML markup:

   <input id="textbox" type="text"  size="25">
   <a class="button" href="http://www.google.com" id='searchlink'>Search</a>
0
source

All Articles