简体   繁体   中英

Can't go to a url in javascript

I am a total noob to web programming (Started just now). I know C, C++ and x86-assenbly (a little bit). I wanna create my own home page for my browser. It's very basic html for the most part but I want a search bar on the top that redirects to duckduckgo with relevant results and that's where the problem arises. The code I'm trying:

<form>
    <input type="text" id="query"/>
    <button id="button" class="button" onclick="openInDuck()">Search</button>
</form>
<script>
    function openInDuck(){
        var x= "https://duckduckgo.com/?q=";
        x += document.getElementById("query").value;
        window.location = x;
    }
</script>

And yeah, I forgot, I am using qutebrowser on archlinux if that matters. Thanks in advance.

You are missing .href on your redirect. Also you should change the button type to button instead of the default;

 function openInDuck() { var x = "https://duckduckgo.com/?q="; x += document.getElementById("query").value; window.location.href = x; } 
 <form> <input type="text" id="query" /> <button id="button" class="button" onclick="openInDuck()" type="button">Search</button> </form> 

Do note that it wouldn't be ideal to redirect the user if you just need to do a search through a different api.

You can use the below

function openInDuck()    {
    var    x="https://duckduckgo.com/?q=";
    x    +=    document.getElementById("query").value;
    window.open(x);
}

Problem is that your form is submitted when clicking the button, like this it works :)

<input type="text" id="query" /> 
<button id="button" class="button" onclick="openInDuck()">Search</button>

<script>
    function openInDuck() {
        var x = "https://duckduckgo.com/?q=";
        x += document.getElementById("query").value;
        window.location = x;
    }
</script>

You are close to the solution. In the JS code, you must add .href after window.location to set the new href (URL) for the current window. In the HTML code, I suggest you use the onsubmit attribute to send the form with an input type="submit" :

 function openInDuck() { var x = "https://duckduckgo.com/?q="; x += document.getElementById('query').value; window.location.href = x; return false; // Prevent the form submission } 
 <form onsubmit="return openInDuck()"> <input type="text" id="query"> <input type="submit" id="button" class="button" value="Search"> </form> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM