Skip to content
Advertisement

How to add variable inside google URL in Javascript? I have tried but in Google it shows up meaning of “Undefined”

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”.

function search(){
    var x = document.getElementById("search").value;
    const url = "https://www.google.com/search?q="+ x +"&oq="+ x +"&aqs=chrome..69i57j69i58.1760j0j7&sourceid=chrome&ie=UTF-8";
    var win = window.open(url);
}

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.

function search(query){
    window.open("https://www.google.com/search?q=" + query)
}

Or stick with your code but set a default value in the event that the selector does not return a match

function search(){
    let x = document.getElementById("search").value;

    if(x){ 
        const url = "https://www.google.com/search?q=" + x
        let win = window.open(url);
    }
    else {
        console.log("No elements had the search id")
    }
}

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement