How to Redirect to another Page with Multiple Parameters in JavaScript

← PrevNext →

We often pass data between web pages as information in the form of URL parameters (or query strings). A URL can have single or multiple parameters. When redirecting to another page from your JavaScript code, you can pass parameters (single or multiple) to the URL. I’ll show how to redirect to another page with multiple parameters in JavaScript.

To redirect to another page in JavaScript, you can use window.location.href property, window.location will also work and if you want you can use window.open() method. Here’s an example using window.location.href property.

window.location.href = "https://www.encodedna.com/";

Redirect to another Page with Multiple Parameters

Now, to insert multiple parameters to the URL, you’ll have to define parameters with values using the ? (Question mark) and & (ampersand) symbols before redirecting. For example,

<script>
    let redirectPage = () => {
        const url = "https://www yourwebsite com/content/ocncontent?userid=43&contentid=9";
        window.location.href = url;
    }
</script>

In the above example, I am passing two parameters namely userid and contentid. The values are hardcoded. You can however get (or extract) the values for the URL parameters dynamically from textbox or input boxes.

<body>
    <!--I have two textbox for each paremeter.-->
    <p>
        <input type='text' id='book' />
    </p>
    <p>
        <input type='text' id='b_name' />
    </p>
    
    <input type='button' value='Click to Redirect' onclick='redirectPage()' />
</body>

<script>
let redirectPage = () => {
    ' Get textbox values.
    let v1 = document.getElementById('book');
    let v2 = document.getElementById('b_name');
    
    const url = "https://www.encodedna.com/javascript/demo/" +
        "check-if-url-contains-a-given-string-using-javascript.htm?book=" + v1.value  + 
        "&name=" + v2.value;

    window.location.href = url;
}
</script>

The above URL has two parameters book and name, for I am extracting the values from the two input boxes.

Let's execute the above code and see what happens. Click the button below. 👇




That's it. Thanks for reading.

← PreviousNext →