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">
<divclass="form-group"><inputtype="text"><buttonid="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 urlwindow.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 valuevar url = './invalid.html';
$.each(validValues, function(i, validValue) {
if ($myInput.val() === validValue.value) {
url = validValue.url;
returnfalse;
}
});
// Submit the form
$('#my-form').prop('action', url).submit();
alert('Redirecting to ' + url);
});
<formclass="form-inline"id="my-form"><divclass="form-group"><inputtype="text"id="my-input"><buttontype="submit"id="my-button">Go</button></div></form><scriptsrc="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"