如何获取表单提交按钮以保存到localStorage

时间:2017-06-24 23:02:54

标签: javascript html css

我是初学者,正在试图弄清楚如何让它发挥作用。我有一个表单,我希望提交按钮能够保存到localStorage。到目前为止,这就是我所拥有的。

<script>
function storeRecipe() {
    localStorage.setItem($("#recipe-name").val(), $("#recipe-
      description").val());
  console.log(Object.keys(localStorage));
}
</script>

<b>Recipe Name:</b>
<br>
<textarea id="recipe-name" rows="1" cols="35"></textarea>
<br><br>
<b>Recipe Description:</b>
<br>
<textarea id="recipe-description" rows="15" cols="35"></textarea>
<br><br>
<input type="submit" value="Send Recipe" onClick="storeRecipe()">

2 个答案:

答案 0 :(得分:0)

使用Vanilla Javascript解决方案

function storeRecipe() {
    let name = document.getElementById("recipe-name").value;
    let description = document.getElementById("recipe-description").value
    localStorage.setItem(name, description);
}

避免使用event.preventDefault()提交默认行为或更改按钮的类型,我建议第二个:

<button type="button" value="Send Recipe" onClick"storeRecipe()">Submit</button>

答案 1 :(得分:0)

提交后,您可以停止提交表单并将每个输入字段保存为localStorage密钥。工作jsfiddle:https://jsfiddle.net/mr4ms4zp/。在Mac上打开控制台cmd+opt+i以查看已更改的localStorage对象。

<form method="POST">
  <b>Recipe Name:</b>
  <br>
  <textarea id="recipe-name" rows="1" cols="35"></textarea>
  <br><br>
  <b>Recipe Description:</b>
  <br>
  <textarea id="recipe-description" rows="15" cols="35"></textarea>
  <br><br>
  <input type="submit" value="Send Recipe">
</form>

<script>
  document.querySelector('form').onsubmit = function(e) {
    e.preventDefault();
    var name = document.querySelector('#recipe-name').value;
    var description = document.querySelector('#recipe-description').value;
    localStorage["name"] = name;
    localStorage["description"] = description;
    console.log(localStorage);
  }
</script>