Reputation: 79
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>
</div>
</form>
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 example.com/something.html
on form submit, or "STRING2" to example.com/otherpage.html
.
But invalid strings would need to go to a page like "example.com/invalid.html."
The most useful thing I've seen so far is this guide: http://www.dynamicdrive.com/forums/showthread.php?20294-Form-POST-redirect-based-on-radio-button-selected
<script type="text/javascript">
function usePage(frm,nm){
for (var i_tem = 0, bobs=frm.elements; i_tem < bobs.length; i_tem++)
if(bobs[i_tem].name==nm&&bobs[i_tem].checked)
frm.action=bobs[i_tem].value;
}
</script>
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.
Upvotes: 0
Views: 2707
Reputation: 792
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.
Upvotes: 1
Reputation: 14004
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>
Upvotes: 0