我试图将表单数据作为json数组附加到localstorage中,但它没有工作。
这是我的表格
<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>
这是我想要保存的内容。
{
"info": [
{
"name": "John",
"icon": "icon1.png"
},
{
"name": "Daniel",
"icon": "icon2.png"
}
]
}
我尝试了什么
$("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))
})
答案 0 :(得分:0)
这是你应该做的事情
var yourObject = {
"info": [{
"name": "John",
"icon": "icon1.png"
},{
"name": "Daniel",
"icon": "icon2.png"
}]
}
localStorage.setItem('yourObject', JSON.stringify(yourObject));
它会将给定的json存储在localstorage中。
答案 1 :(得分:0)
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>