So i was working on a project where i needed to make a search box by which when a button is clicked it searches the value in the input in new tab on google so i wrote some code to make it possible.
In order to make the google search by my page i wrote the following code
Html –
<div class="search-container">
<form>
<img src="imgs and icons/google.png" alt="" class="g-icon">
<input class="search" type="text" name="myInput"/>
<button id="search-button" onclick="googleSearch()"><img src="imgs and icons/search.png" class="search-icon" alt=""></button>
</form>
</div>
and here is javascript-
function googleSearch()
{
var text=document.getElementsByClassName("search").value;
var cleanQuery = text.replace(" ","+",text);
var url='http://www.google.com/search?q='+cleanQuery;
window.location.href=url;
}
Please tell me what mistake is there in this code and why is it not working
2
Answers
document.getElementsByClassName
return isNodeList
More info: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
String.prototype.replace()
only accept 2 parametersMore info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
Good afternoon!
So the first thing you should take a look at is what your
var text
is actually storing. getElementsByClassname returns an array of elements (HTMLCollection).You can either index it for it’s first element like so
Note: querySelector(‘[css like string]’) uses the same syntax as your css selectors so
.name
will look for elements with class of name and#name
will look for elements with the id of nameEither way hope any of these help you out!
Edit; the replacements of whitespace characters is redundant if you only intend to use it with google,
?q=test value
yields the same results as?q=test+value
or?q=test%20value
Edit 2;
In order to open the url in a new tab/window you cannot use
window.location.href
, window in this case refers to your current window instance, that’s why they’ve provided us withwindow.open(url, target)
target is used to indicate where the window should open to, usually
_blank
, see target keywords for a more detailed explanation