我已将值从html格式存储到localstorage,并且当我将数据从localstorage返回到表单进行编辑时,数据将像应该的那样进入输入文本字段,但不会出现在下拉列表或复选框字段中。
我需要怎么做才能在下拉列表或复选框字段中获取值?复选框具有保存为数组的多个值,因此需要将其分开。
if (localStorage.hasOwnProperty('key')) {
$(function editform() {
var lsdata = JSON.parse(localStorage.getItem('key'));
$('#formid').val(lsdata.FormID);
$('#createdate').val(lsdata.CreateDate);
$('#formfiller').val(lsdata.FormFiller);
$('#customerlist').val(lsdata.CustomerName); //dropdown
$('#contact').val(lsdata.CustomerContact);
$('#worklist').val(lsdata.WorkName); //dropdown
$('#readytodate').val(lsdata.ReadyToDate);
$('#instructions').val(lsdata.Instructions);
$('#amount').val(lsdata.Amount);
$('#amountpcs').val(lsdata.PcsAmount);
$('#chargefull').val(lsdata.ChargeFull);
$('#chargepcs').val(lsdata.ChargeByPcs);
$('#freightcost').val(lsdata.FreightCost);
$('#materiallist').val(lsdata.MaterialName); //checkbox with multiple options
// localstorage value
{
"$id": "1",
"Customer": null,
"Material": null,
"Status": null,
"Work": null,
"FormID": 150,
"CreateDate": "2019-09-17T00:00:00",
"FormFiller": "JOkuMuu",
"CustomerID": null,
"CustomerName": "Wsoy",
"CustomerContact": "Masa",
"WorkID": null,
"WorkName": "Lajitelmapakkaus",
"ReadyToDate": "2019-09-19T00:00:00",
"Instructions": "Tarkasta kirjat ",
"Amount": 50,
"PcsAmount": null,
"ChargeFull": null,
"ChargeByPcs": null,
"FreightCost": null,
"MaterialID": null,
"MaterialName": "Xpohja,Tarra",
"WorkHoursWR": null,
"WorkHoursIT": null,
"WorkHoursCS": null,
"StatusID": null
}
答案 0 :(得分:0)
您使用的hasOwnProperty
不是LocalStorage
专用的方法,而是Object
。相反,您应该使用setItem/getItem
LocalStorage
方法
// localstorage value
var data = {
"$id": "1",
"Customer": null,
"Material": null,
"Status": null,
"Work": null,
"FormID": 150,
"CreateDate": "2019-09-17T00:00:00",
"FormFiller": "JOkuMuu",
"CustomerID": null,
"CustomerName": "Wsoy",
"CustomerContact": "Masa",
"WorkID": null,
"WorkName": "Lajitelmapakkaus",
"ReadyToDate": "2019-09-19T00:00:00",
"Instructions": "Tarkasta kirjat ",
"Amount": 50,
"PcsAmount": null,
"ChargeFull": null,
"ChargeByPcs": null,
"FreightCost": null,
"MaterialID": null,
"MaterialName": "Xpohja,Tarra",
"WorkHoursWR": null,
"WorkHoursIT": null,
"WorkHoursCS": null,
"StatusID": null
}
localStorage.setItem('key', JSON.stringify(data));
if (fetchedData = localStorage.getItem('key')) {
console.log('Item found!', fetchedData);
}else{
console.log('Item NOT found!');
}
请注意,由于会引发same origin
错误,因此此代码段无效。
希望这会有所帮助。