我在表格中有几个可选的输入字段。我想在提交后保留它们的输入值。
我正在阅读此JS input type date field, keep values selected after form submission,但是由于输入字段都是可选的,因此在Web控制台中出现can not set property value of null
的错误。
<form class="cat_select" onsubmit="setCate()">
<input class="l2" name="l2" id="l2" type="text" style="width:30%">
<input class="l3" name="l3" id="l3" type="text" style="width:50%">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit" id="cat_submit">Submit</button>
</form>
function setCate(){
var l2 = document.getElementById('l2').value;
var l3 = document.getElementById('l3').value;
}
function getl2(){
if (localStorage.getItem("user_selected_l2") !== null) {
return localStorage.getItem("user_selected_l2");
}
}
function getl3(){
if (localStorage.getItem("user_selected_l3") !== null) {
return localStorage.getItem("user_selected_l3");
}
}
//seems that can't set these as null
document.getElementById('l2').value=getl2();
document.getElementById('l3').value=getl3();
答案 0 :(得分:3)
您可以使用条件三元数将null替换为空字符串:
document.getElementById('l2').value = getl2()? getl2() : '';
document.getElementById('l3').value = getl3()? getl3() : '';
或者您可以使用相同的逻辑返回空字符串而不是null:
function getl3(){
if (localStorage.getItem("user_selected_l3") !== null) {
return localStorage.getItem("user_selected_l3")?
localStorage.getItem("user_selected_l3") : '';
}
}