Skip to content Skip to sidebar Skip to footer

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.

Solution 1:

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>
    </div>
</form>
var urlMapping = {
    "STRING1" : "./first.html",
    "STRING2" : "./second.html",
    "STRING3" : "./third.html"
}

$("#submit-form").click(function(){
    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";
    }
});

Note : I added .toUpperCase() to make it case-insensitive, so you have to be careful to define the urlMapping keys ("STRING1",..) in uppercase.


Solution 2:

This should do what you want:

// Define routing:
var validValues = [{
  value: 'STRING1',
  url: './something.html'
}, {
  value: 'STRING2',
  url: './otherpage.html'
}];

var $myInput = $('#my-input');
$('#my-button').click(function(ev) {
  ev.preventDefault(); // Prevent submitting the form already

  // Look for a valid value
  var url = './invalid.html';
  $.each(validValues, function(i, validValue) {
    if ($myInput.val() === validValue.value) {
      url = validValue.url;
      return false;
    }
  });

  // Submit the form
  $('#my-form').prop('action', url).submit();
  alert('Redirecting to ' + url);
});
<form class="form-inline" id="my-form">
  <div class="form-group">
    <input type="text" id="my-input">
    <button type="submit" id="my-button">Go</button>
  </div>
</form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Post a Comment for "Need To Redirect Form To Multiple URLs Based On Input"