May Y
May Y

Reputation: 179

Allow null values while keeping input values after submission

I have several optional input fields in the form. And I would like to retain their input values after submission.

I am reading through this JS input type date field, keep values selected after form submission but as the input fields are all optional, I get error that can not set property value of null in web console.

<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();

Upvotes: 2

Views: 680

Answers (1)

silencedogood
silencedogood

Reputation: 3299

You could use conditional ternary to replace null with an empty string:

document.getElementById('l2').value = getl2()? getl2() : ''; 
document.getElementById('l3').value = getl3()? getl3() : '';

Or you could use the same logic to return an empty string rather than null:

function getl3(){
    if (localStorage.getItem("user_selected_l3") !== null) {
        return localStorage.getItem("user_selected_l3")?
               localStorage.getItem("user_selected_l3") : '';
    }   
}

Upvotes: 3

Related Questions