Javascript localStorage没有从form接收输入

Javascript localStorage not reciving input from form

本文关键字:输入 form localStorage Javascript      更新时间:2023-09-26

我正在从HTML表单保存数据到localStorage。

这是我到目前为止的代码

HTML

<form onSubmit="newRecipe()">
  Recipe Name:<br>
  <input type="text" value="Recipe" name="Recipe"><br>
  Ingredients:<br>
  <input type="text" name="Ingredients" value="Ingredients"><br><br>
  <input type="submit" value="Submit">
</form> 
JavaScript

function newRecipe(){
     var inputrecipe= document.getElementById("Recipe");
     localStorage.setItem("Recipe", JSON.stringify(Recipe));
  var inputingredients= document.getElementById("Ingredients");
  localStorage.setItem("Ingredients", inputingredients.value, JSON.stringify(testObject));
    }
document.getElementById("test").innerHTML = localStorage.getItem("Recipe"); 

我做错了什么?当我提交表单时,我得到一个白屏,没有localStorage保存

您的代码中有一些错误。首先,你不会把id赋值给你想要得到的元素。我稍微修改了一下你的代码,并使用了jQuery(只是因为它打字更快,编写的代码更少)。我还建议遵循正常的命名约定,比如给变量起小写的名字(除非它们是构造函数)和camel大小写。在HTML中,您可能希望尝试将所有内容保持小写并使用-代替。

这还没有从localStorage中读取,也没有显示字段中的值。但它确实挽救了它。我希望你能从面包屑中找出剩下的。:)

HTML:

<form id='form'>
  Recipe Name:<br>
  <input type="text" value="Recipe" name="recipe" id="recipe">
  <br>
  Ingredients:<br>
  <input type="text" name="ingredients" value="ingredients" id="ingredients">
  <br><br>
</form> 
<button>Submit</button>

JS:

$('button').click(function(){
    var name = $('#recipe').val();
  var ingredients = $('#ingredients').val();
  localStorage.setItem(name, ingredients);  
});

你的代码中有一些错误。没有ID为RecipeIngredients的元素

这样修改HTML

<form id="form">
  Recipe Name:<br>
  <input type="text" value="Recipe" name="Recipe" id="Recipe"><br>
  Ingredients:<br>
  <input type="text" name="Ingredients" value="Ingredients" id="Ingredients"><br><br>
  <input type="submit" value="Submit">
</form>

JS

1)当你提交表单时,你需要触发一个函数。

var form=document.getElementById("form");
form.onsubmit=function(){
   //code here
}
2)使用.value属性获取输入的值,如下所示:

var inputrecipe= document.getElementById("Recipe").value;

3)在函数中包含document.getElementById("test").innerHTML = localStorage.getItem("Recipe");

var form=document.getElementById("form");
form.onsubmit=function(){
   alert("it is hitting");
   var inputrecipe= document.getElementById("Recipe").value;
   localStorage.setItem("Recipe", JSON.stringify(inputrecipe));
   var inputingredients= document.getElementById("Ingredients").value;
   localStorage.setItem("Ingredients",JSON.stringify(inputingredients));
   document.getElementById("test").innerHTML = localStorage.getItem("Recipe");
   return false;
}