【问题标题】:How to redirect to another page after click on submit button in form with required inputs单击带有所需输入的表单中的提交按钮后如何重定向到另一个页面
【发布时间】:2019-09-05 08:06:34
【问题描述】:

单击表单中的按钮后,我需要重定向到 index.html。我试过这个:

$("#btn").on("click", function() { 
  window.location.replace("index.html");
  localeStorage.clear();
})

但是在表单中我需要输入,所以当我有一些空的必需输入时,它会重定向,但同时它说我必须写一些东西来输入。

表单提交成功后,我需要重定向到 index.html。提交订单后就像在网上商店一样

【问题讨论】:

  • 您需要在此表单提交的页面上进行重定向。不是这个页面。

标签: javascript jquery html


【解决方案1】:

首先,如果您希望在重定向之前首先验证表单,您需要将事件放在表单的submit,而不是按钮的click

其次,表单提交时在JS中进行重定向是多余的;只需将表单的action 设置为您希望将用户发送到的位置。

考虑到上述情况,试试这个:

<form id="yourForm" action="index.html">
  <input type="text" name="foo" required />
  <!-- Some more 'required' form controls... -->

  <button type="submit">Submit</button>
</form>
$("#yourForm").on("submit", function() { 
  localeStorage.clear();
});

【讨论】:

    【解决方案2】:

    您可以做的是在重定向之前验证输入是否存在:

    $("#btn").on("click", function() { 
       // do some checks
    
       //if checks ok call redirect, if ko returns
       window.location.replace("index.html");
       localeStorage.clear();
    })
    

    【讨论】:

      【解决方案3】:

      您可以验证值,使用 fetch 发送表单,然后重定向。

      (您可以在重定向之前添加一些服务器响应的gestion。例如“登录已经在数据库中......)

      $("#btn").on("click", function() { 
        const verif = *verifAndFormat(...)* // function that return json like {valid:true , data:... }
        if( verif.valid ){
          fetch( URL , {method:'POST', body: verif.data} )
          .then( resp =>{
            /*some operations*/
            localeStorage.clear();
            window.location.replace("index.html");
          })
          .catch( err => /*error gestion*/
        }else{
          /*Invalid value gestion*/
        }
      })
      

      【讨论】:

        【解决方案4】:
         $(function(){  
            $('#btn').On('click', function() {
        window.location.href="../index.html";
        }
        }
        

        您也可以在点击事件上调用它的表单 html 编码来调用函数提交并从中重定向.. html编码

        <input type="button" id="btn" onclick="submit()"/>
        

        Javascript 编码

        function submit(){
        window.location.replace("http://webpagename.index.html");
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-06-26
          • 1970-01-01
          • 2012-04-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-06-14
          相关资源
          最近更新 更多