需要根据输入将表单重定向到多个 URL [英] Need to redirect form to multiple URLs based on input
问题描述
我有一个基本的 HTML 表单,我需要帮助创建一些 JS 以根据文本字段中键入的字符串将我的表单重定向到不同的 URL.
</表单>
将有 3 或 4 个文本字符串 - 要在输入字段中输入 - 它们是有效的",我需要它们使表单重定向到网站上的各个页面.
例如,输入有效字符串STRING1"将使页面在表单提交时重定向到 example.com/something.html
,或将STRING2"重定向到 example.com/otherpage.html
.
但是无效的字符串需要转到example.com/invalid.html"之类的页面.
到目前为止我看到的最有用的东西是这个指南:http://www.dynamicdrive.com/forums/showthread.php?20294-Form-POST-redirect-based-on-radio-button-selected
在那个代码中,每个收音机都有一个分配给它的值.但这对文本字段或在字符串无效时进行全面重定向无济于事.
非常感谢您的帮助.
您可以在对象中定义路由:
</表单>
var urlMapping = {"STRING1" : "./first.html","STRING2" : "./second.html","STRING3" : "./third.html"}$("#submit-form").click(function(){var input = $("input").val().trim().toUpperCase();如果(urlMapping.hasOwnProperty(输入)){window.location = urlMapping[输入];}别的 {//如果找不到url,重定向到默认urlwindow.location = "./default.html";}});
注意:我添加了 .toUpperCase()
使其不区分大小写,因此您必须小心定义 urlMapping 键(STRING1",..) 大写.
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.
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.
这篇关于需要根据输入将表单重定向到多个 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!