user3236756 user3236756 - 2 years ago 306
jQuery Question

Need to redirect form to multiple URLs based on input

I have a basic HTML form and I need help creating a bit of JS to redirect my form to different URLs based on the string typed in a text field.

<form class="form-inline">
<div class="form-group">
<input type="text">
<button type="submit">Go</button>

There will be 3 or 4 strings of text - to be entered in the input field - that are "valid" and I need them to make the form redirect to various pages on the site.

For instance, typing valid string "STRING1" would make the page redirect to
on form submit, or "STRING2" to

But invalid strings would need to go to a page like ""

The most useful thing I've seen so far is this guide:

<script type="text/javascript">
function usePage(frm,nm){
for (var i_tem = 0, bobs=frm.elements; i_tem < bobs.length; i_tem++)

In that code, each radio has a value assigned to it. But this doesn't help with text fields or having a blanket redirect if the string is invalid.

Thanks so much for your help.

Answer Source

You could define the routes in an object :

<form class="form-inline">
    <div class="form-group">
         <input type="text">
         <button id="submit-form" type="button">Go</button>
var urlMapping = {
    "STRING1" : "./first.html",
    "STRING2" : "./second.html",
    "STRING3" : "./third.html"

    var input = $("input").val().trim().toUpperCase();
    if (urlMapping.hasOwnProperty(input)){
        window.location = urlMapping[input];
    else {
        //if url not found, redirect to default url
        window.location = "./default.html";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download