简体   繁体   English

不使用event.preventDefault阻止html5表单提交

[英]Prevent html5 form submit without using event.preventDefault

About Browser Suggested Inputs 关于浏览器建议的输入

eg when a user enters "John" into 例如,当用户在其中输入“ John”

 <form> <input type="text" name="firstName"/> </form> 

and submits the form, then when they revisit this page, "John" will be a suggested input for this field. 并提交表单,然后当他们重新访问该页面时,“ John”将是该字段的建议输入。

The Problem 问题

I'm trying to take advantage of the input field suggestions in chrome, but I don't want the page to reload. 我试图利用chrome中的输入字段建议,但我不希望页面重新加载。 I have a single page application that will record the form submission and store it in a global state already. 我有一个单页应用程序,它将记录表单提交并将其存储在全局状态中。

Using event.preventDefault on the submit callback of the form element stops the page from reloading but it also prevents the new suggestions from being recorded. 在form元素的Submit回调上使用event.preventDefault可以阻止重新加载页面,但也可以防止记录新建议。

So how can I trigger the browser to save the user input without a refresh? 那么,如何触发浏览器以保存用户输入而无需刷新?

You could easily manage the auto fill behavior using HTML5 datalist or/and localstorage . 您可以使用HTML5 数据列表或/和localstorage轻松管理自动填充行为。

 <label for="nameList">Names</label> <input type="text" name="name" id="nameList" list="names"> <datalist id="names"> <option value="John"> <option value="Mickey"> <option value="Donald"> </datalist> 

If you want to update the fields or perform a custom datalist for each user, you could use localstorage to store the list. 如果要为每个用户更新字段或执行自定义数据列表,则可以使用localstorage来存储列表。 Here an example: 这里是一个例子:

<label for="nameList">Names</label>
<input type="text" name="name" id="nameList" list="names">
<datalist id="names">
</datalist>
  <button id="click">click</button>
</body>
  <script>
    var names = [];
document.addEventListener('DOMContentLoaded', function(){

  if(localStorage.getItem("names")){
    names = JSON.parse(localStorage.getItem("names"));//<-- names already stored    
  }
  var datalist = document.getElementById("names")
  var options = "";
  names.map(o=>{
    options += '<option value="'+o+'" />';//<-- build custom datalist
  })

  datalist.innerHTML = options; 

}, false);

var frm = document.getElementById("click");
frm.addEventListener("click", function(){
  names.push(document.getElementById("nameList").value);//<-- set new names
  localStorage.setItem("names",JSON.stringify(names));  

});
  </script>

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

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