Search code examples
javascriptformsuser-inputassignwindow.location

window.location.assign() navigate to user input of url?


I need to use Javascript window.location.assign() to take input from a user in an inputbox and once a button is clicked the user will be taken to the URL they entered in that inputbox- I am having difficulty finding this online. I am assuming I would need to add a function to my script (not shown).

    <form style="padding-top: 20px;">
        URL: <input type="url" name="url">
        <input type="button" value="GO!" onclick="newUrl()">
    </form>

Solution

  • First, instead of putting the function in "onclick" in the button, I suggest putting it on the form element's "onsubmit" handler. That way, a simple "Enter" key can also cause the navigation.

    Second, since we're putting the callback on the form, the form's action should changed to 'javascript', like this:

    <form style="padding-top 20px;" action="javascript://#" onsubmit="newUrl(this.elements['url'].value)">
        URL: <input type="text" name="url">
        <input type="submit" value="GO!">
    </form>
    

    I've put the url in the first parameter of the "newUrl" function, for ease of writing.

    Finally, your "newUrl" function:

    function newUrl(url) {
        window.location.assign(url);
    }