SutterCane SutterCane - 3 months ago 9
HTML Question

I want to make a function with JS for take a value of input and search it on Google

I have an input tag and a select tag (with some option tags). I'm trying to make a function with JavaScript that executes when the user clicks any option tag (inside of the select), and this will be open the site clicked by the user (for example, Google) and search the text that he just writed in the input (adding 'search?q=' + the value of the input). The result will be 'http://google.com/search?q=' + the value on the input, opening in a new tab.

For the moment I have this:

HTML code:

<form class="" submit="">
<input type="text" id="search-nav" placeholder="Search on">
<select class="search-on" onChange="searchIn(this)">
<option value="">Select</option>
<option value="google">Google</option>
<option value="youtube">YouTube</option>
<option value="bing">Bing</option>
<option value="amazon">Amazon</option>
</select>
</form>


JS code:

function searchIn(selected) {
var value = selected.value;
var text = getElementById('search-nav').value;

if (value == selected.value) {
window.open('https://www.google.es/search?q=' + text);
}
}


A possibility that I consider is working with the submit attribute, executing some *.js. Any idea?

Answer

Not sure if I understand your question, but you could create an object with the options' values as keys if you want to have the linked stored and available.

var links = {
    google: 'https://www.google.es/search?q=', 
    amazon: '<link to amazon>',
    // ...
};

And use it in your function:

function searchIn(selected) {
   var value = selected.value;
   var text = getElementById('search-nav').value;

   window.open(links[value] + text);
}

var links = {
    google:  'https://www.google.es/search?q=', 
    amazon:  '<link to amazon>',
    youtube: '<link to youtube>',
    bing:    '<link to bing>'
};

function searchIn(el) {
   var value = el.target.value;
   var text = document.getElementById('search-nav').value;

   // you want to uncomment the next line to open the window;
   // window.open(links[value] + text);
  
   alert('your link would be: ' + links[value] + text);
   
}

document.getElementById("searchSelection").addEventListener("change", searchIn, false);
<form class="" submit="">
   <input type="text" id="search-nav" placeholder="Search on">
   <select class="search-on" id="searchSelection">
      <option value="">Select</option>
      <option value="google">Google</option>
      <option value="youtube">YouTube</option>
      <option value="bing">Bing</option>
      <option value="amazon">Amazon</option>
   </select>
</form>
JS code: