我需要创建2个输入框,带有提交按钮的文本区域。我必须使用jQuery序列化数组和JSON本地存储。单击提交按钮后,字段应为空以供其他用途,并且发布的数据需要显示在" DivPrintValue" (IMP:提交后需要在页面上显得整洁干净),刷新页面后也需要保存。这就是我到目前为止所做的:
<div id="submitted">
<h3>Submitted Ideas</h3>
<div id="DivPrintValue">
</div>
</div>
<form id="titleForm">
<h3>Add Idea</h3><br>
<input type="text" name="title" id="title" placeholder="Title" size="38" required />
<br>
<textarea name="description" id="description" placeholder="description" cols="29" required oninvalid="this.setCustomValidity('write your message here!')"></textarea>
<br>
<input type="text" name="category" id="category" placeholder="category" size="38" />
<br><br>
<input type="submit" value="add idea">
</div>
</form>
localStorage的:
$(function () {
// Array
var myIdeas = [];
function printToScreen(myValues) {
if (myIdeas.length > 0) {
$("#DivPrintValue").html('');
myValues.forEach(function (item, index) {
item.forEach(function (itm, indx) {
$("#DivPrintValue").append(itm.name + " -" + itm.value + "<br>");
})
})
}
}
//page load or refreash
if (localStorage.getItem("ideas") !== null) {
var localValues = JSON.parse(localStorage.ideas);
if (myIdeas.length <= 0) {
myIdeas = localValues;
}
printToScreen(localValues);
}
$("#titleForm").submit(function (e) {
e.preventDefault();
var formValues = $(this).serializeArray();
myIdeas.push(formValues);
localStorage.setItem("ideas", JSON.stringify(myIdeas));
var myValues = JSON.parse(localStorage.ideas);
printToScreen(myValues);
this.reset();
})
})
答案 0 :(得分:1)
您可以创建一个变量来存储$(this).serializeArray()
作为参数JSON.stringify()
,.append()
值存储到#submitted
,设置值localStorage
,调用{{1 .reset()
元素
form
$("form").submit(function(e) {
e.preventDefault();
// serialize `form`
var values = $(this).serializeArray();
values.forEach(function(item, index) {
$("#submitted").append(item.name + " " + item.value + "<br>");
})
// reset `form`
this.reset();
// set `values` at `localStorage`
// if (!localStorage.form)
localStorage.setItem("form", JSON.stringify(values))
})