Home > Blockchain >  How to redirect the user to a new website after they submit the <form>?
How to redirect the user to a new website after they submit the <form>?

Time:02-20

I'm trying to redirect the user to a new webpage depending on their form input using JavaScript if the user types in the form input something so I want him to be taken to like website.com/something and if he types else then I want him to be taken to website.com/else so basically I want to store the input of '#inputbox' as he clicks enter or the search button and I want then to redirect the user to a website using let website = 'website.com/' input then redirect them to website.com/input

<form action="#" type="submit" id="form">
   <input type="text" name="search" id="inputbox">
   <input type="submit" value="Go To" id="button">
</form>

CodePudding user response:

I was able to get it to work using this code:

    document.addEventListener ('input', function() {
        let form = document.getElementById("form");
        let text = document.getElementById("inputbox").value;
        let response = 'website.com/'   text;
        form.onsubmit = function() {
            window.location = response;
            return false;
        };
    });

CodePudding user response:

In your JavaScript file (app.js in the example below), link to your button and the input box:

const linkButton = document.querySelector('#button');  // link to button
const inputBox = document.querySelector('#inputbox');  // link to inputbox

linkButton.addEventListener('click', evt => {
    const routeUrl = inputBox.value;                                // value from the input box
    let baseUrl = evt.target.getAttribute('href');                  // get href fom btn href attrib
    baseUrl = baseUrl.slice(-1) === '/' ? baseUrl : baseUrl   '/';  // add a trailing slash
    window.open(baseUrl   routeUrl, target='_blank');               // target='_self' opens the link in the same tab
});

And, in your HTML:

<form action="#" type="submit" id="form">
    <input type="text" name="search" id="inputbox">
    <input type="button" value="Go To" id="button" href="https://your.com/">
</form>

And link to JavaScript just before the closing body tag:

<script src="app.js"></script>

This should work, if that's the route you choose to take.

  • Related