我已将值从 html 表单存储到本地存储,当我将数据从本地存储返回到表单进行编辑时,数据将像应有的那样进入输入文本字段,但不会进入下拉列表或复选框字段。
我需要做什么才能在下拉列表或复选框字段中获取值?复选框有多个值保存为数组,因此需要将它们分开。
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
}
最佳答案
您使用的hasOwnProperty
不是LocalStorage
特有的方法,而是Object
。相反,您应该使用 LocalStorage
setItem/getItem
方法
// 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!');
}
请注意,此代码段将不起作用,因为将抛出同源
错误。
希望这有帮助。
关于javascript - 无法从 LocalStorage 获取下拉列表的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57969232/