Input field data not deleted once add

65 Views Asked by At

I have a form which is including with cakephp3 and JS. I have a question how can i store data into the input field? There is some condition for this task, if once user add input into the input field these data will not remove , if the page is load by someone or close the browser and again get back to that page user will get same data in input field what he type, but when he submit the form then only data will remove from the form. any possible solution for this.

1

There are 1 best solutions below

0
WizardOfOz On

As mentioned in the comments, you can handle this by;

  1. Saving the input.value to localstorage

  2. Set your input value to whatever is in local storage

  3. On submit you clear localstorage

    // Get the input field let input = document.getElementById("myInput"); let submit = document.getElementById('submit');

    // Save data to local storage on keyup or keydown
    input.addEventListener('keydown', (e) => {
      if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
       e.preventDefault(); 
       localStorage.setItem('Name', JSON.stringify(input.value))
      }
    });
    
    //Populate input data with whatever is in localstorage
    function populateUI(){
        if (localStorage.getItem("Name") !== null) {
          input.value = JSON.parse(localStorage.getItem('Name'))
        }  
    }
    
    // Reset localstorage and input field value after submit
    submit.addEventListener('click', () => {
       localStorage.removeItem("Name");
       input.value = ''
    }, false)
    
    populateUI();