I'm trying to append form data as json array in localstorage but it didn't work.
Here my form
<form>
<label>Choose a option</label>
<input type="radio" name="icon" value="icon1.png">
<input type="radio" name="icon" value="icon2.png">
<input type="radio" name="icon" value="icon3.png">
<label>Name</label>
<input type="text" name="name" placeholder="Your Name">
<button type="submit" id="save">Save</button>
</form>
Here's what i'm trying to save.
{
"info": [
{
"name": "John",
"icon": "icon1.png"
},
{
"name": "Daniel",
"icon": "icon2.png"
}
]
}
What I try
$("form").submit(function(e) {
e.preventDefault();
// serialize `form`
var values = $(this).serializeArray();
values.push(function(item, index) {
$("#test").append(item.name + " " + item.value + "<br>");
})
localStorage.setItem("jsonFav", JSON.stringify(values))
})
Here's what you should do
var yourObject = {
"info": [{
"name": "John",
"icon": "icon1.png"
},{
"name": "Daniel",
"icon": "icon2.png"
}]
}
localStorage.setItem('yourObject', JSON.stringify(yourObject));
It will store given json in localstorage.
var results=localStorage.getItem("json") || {info: []}; $(window).submit(function(evt) { evt.preventDefault(); results["info"].push({ name: $('input[name=name]').val(), icon: $('input[name=icon]:checked').val() }); localStorage.setItem("json", results); }); // To get json as string use JSON.stringify(jsonValue);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <label>Choose a option: </label> <input type="radio" name="icon" value="icon1.png"> <input type="radio" name="icon" value="icon2.png"> <input type="radio" name="icon" value="icon3.png"><br> <label>Name:</label> <input type="text" name="name" placeholder="Your Name"><br> <button type="submit" id="save">Save</button> </form>
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.