根据选择选项元素将表单重定向到不同的URL但重定向后未选中

时间:2015-03-02 11:18:40

标签: javascript php jquery html ajax

如果选择除选项之外的任何选项,我需要让表单重定向到另一个网址。然后显示所选的选项。

提前谢谢

 <html> 
    <head>      
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>        
  </head>
   <body>    
        <form method='post'>   
            <select id="selectbox">  
                <option value="index.html" selected>Home</option>
                <option value="?hello=about" >Abut Us</option>
                <option value="?hello=contact" >Contact Us</option>
                <option value="?hello=blog">Blog</option>   
            </select>   
        </form>  

   <script>
        $(function(){
          // bind change event to select
          $('#selectbox').bind('change', function () {
              var url = $(this).val(); // get selected value
              if (url) { // require a URL
                  window.location = url; // redirect
              }
              return false;
          });
        });
    </script> 
    </body>  
    </html>

4 个答案:

答案 0 :(得分:1)

只需使用

if (url) { // require a URL
    window.location.href = url; // redirect
}

因为在选项值中您没有传递完整的URL。

答案 1 :(得分:1)

因此,假设您的URL具有查询字符串,例如&#34;?hello = about&#34;,&#34;?hello = xxx&#34;以下应该有效。在selectbox绑定方法之后删除此代码。请记住,我没有测试过此代码。

var option = location.search.replace(/(^\?hello=[^&#]+).*?$/i, "$1");
$('#selectbox').val(option);

答案 2 :(得分:0)

试试这个:

$(function(){
    // bind change event to select
    $('#selectbox').bind('change', function () {
        var url = $(this).val(); // get selected value
        if (url) { // require a URL
            $( 'form' ).attr( 'action', url ).submit();
        }
        return false;
    });
});

答案 3 :(得分:0)

我假设您希望表单比您的问题中指示的更多,否则这只是一个基本的跳转导航。如果您要传输更多数据,那么window.location将不会从表单中发布该数据。您需要执行以下操作:

$(function(){
    // bind change event to select
    $('#selectbox').bind('change', function () {
        var url = $(this).val(); // get selected value
        if (url) { 
            // set the 'action' attribute to the
            // value of the url var and submit the form.
            $('form').attr('action', url).submit();
        }
        return false;
    });

});