提交表单时将数据保存到localStorage

时间:2012-05-03 05:14:07

标签: forms submit local-storage

是否可以将数据从表单保存到localStorage并提交表单?我需要提交表单,但将值保存到localStorage也很重要。我怎样才能做到这一点?

以下是我对表单和localStorage的代码,但这不提交表单。它只是保存了值。

<label for="server"> Server: </label> 
<input type='text' name="server" id="saveServer"/> 
<button onclick="save_data()" type="button" value="Save" id="Save" data-theme="a">Save</button> 
<script> function save_data()
{ var input = document.getElementById("saveServer");
localStorage.setItem("server", input.value); 
var storedValue = localStorage.getItem("server"); } 

1 个答案:

答案 0 :(得分:2)

当然,但您可能希望稍微改变一下方法,以便在提交表单时将save_data 称为

<form onsubmit="save_data()">
  <!-- The rest of your form goes here -->
  <button type="button" value="Save" id="Save" data-theme="a">Save</button> 
</form>

<script> 
function save_data() {
  var input = document.getElementById("saveServer");
  localStorage.setItem("server", input.value); 
  var storedValue = localStorage.getItem("server"); 
  // etc..
}
</script>