简体   繁体   中英

Prevent html5 form submit without using event.preventDefault

About Browser Suggested Inputs

eg when a user enters "John" into

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

The Problem

I'm trying to take advantage of the input field suggestions in chrome, but I don't want the page to reload. 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.

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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