繁体   English   中英

单击带有必需输入的表单中的提交按钮后,如何重定向到另一页

[英]How to redirect to another page after click on submit button in form with required inputs

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

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

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

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

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

$("#btn").on("click", function() { 
   // do some checks

   //if checks ok call redirect, if ko returns
   window.location.replace("index.html");
   localeStorage.clear();
})

首先,如果您希望在重定向之前首先验证表单,则需要将事件放置在表单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();
});

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

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

$("#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*/
  }
})
 $(function(){  
    $('#btn').On('click', function() {
window.location.href="../index.html";
}
}

而且您也可以在click事件上将其称为html编码形式,以调用函数提交并从中重定向。html编码

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

Javascript编码

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM