I am a beginner and am trying to figure out how to get this to work. I have a form and I want the submit button to be able to save to the localStorage. So far, this is what I have.
<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()">
Solution with Vanilla Javascript
function storeRecipe() {
let name = document.getElementById("recipe-name").value;
let description = document.getElementById("recipe-description").value
localStorage.setItem(name, description);
}
Avoid the submit default behavior with event.preventDefault() or change the type of the button, i would recommend the second one:
<button type="button" value="Send Recipe" onClick"storeRecipe()">Submit</button>
Upon submit, you can stop the submission of the form and save each input field into as a localStorage key. Working jsfiddle: https://jsfiddle.net/mr4ms4zp/ . Open the console cmd+opt+i
on macs to see the changed localStorage
object.
<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>
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.