我有一个基本的HTML表单,我需要帮助来创建一些JS,以根据文本字段中键入的字符串将表单重定向到不同的URL。

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


将在输入字段中输入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

<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>


在该代码中,每个无线电都有一个为其分配的值。但这对于文本字段或字符串无效的情况下的重定向无济于事。

非常感谢你的帮助。

最佳答案

您可以在对象中定义路线:

<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";
    }
});


注意:我添加了.toUpperCase()使其不区分大小写,因此必须小心定义大写的urlMapping键(“ STRING1”,..)。

关于javascript - 需要根据输入将表单重定向到多个URL,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37769132/

10-11 22:15
查看更多