2

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();
1
  • 1
    You can return empty string from the getl2() and getl3() function if it finds null. Commented Oct 9, 2019 at 13:36

1 Answer 1

3

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") : '';
    }   
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I find handling null values in the function does the trick.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.