When I run it shows me the meaning of “Undefined” in Google.
When I run it, it performs a Google search for the word “Undefined”.
JavaScript
x
6
1
function search(){
2
var x = document.getElementById("search").value;
3
const url = "https://www.google.com/search?q="+ x +"&oq="+ x +"&aqs=chrome..69i57j69i58.1760j0j7&sourceid=chrome&ie=UTF-8";
4
var win = window.open(url);
5
}
6
Advertisement
Answer
If the #search
field cannot be found document.getElementById()
returns undefined, which is used as part of the search query.
You can write a function like this, which will allow you to pass in a value to be searched.
JavaScript
1
4
1
function search(query){
2
window.open("https://www.google.com/search?q=" + query)
3
}
4
Or stick with your code but set a default value in the event that the selector does not return a match
JavaScript
1
13
13
1
function search(){
2
let x = document.getElementById("search").value;
3
4
if(x){
5
const url = "https://www.google.com/search?q=" + x
6
let win = window.open(url);
7
}
8
else {
9
console.log("No elements had the search id")
10
}
11
}
12
13