hamed dehghan
hamed dehghan

Reputation: 599

how to remember inputs value by using local storage?

I have tried to use local storage to remember the input's value after refreshing page. but my code does not work.

here is the HTML code

<input type="text" name="name" onkeyup="saveValue(event)"/> 
<input type="text" name="name" onkeyup="saveValue(event)"/> 
<input type="text" name="age" onkeyup="saveValue(event)"/> 

and here is javascript

<script type="text/javascript">
var nameArr = ["name"];
var inputs = document.getElementsByName('name');
inputs.forEach(function(el){
    el.value = getSavedValue(el);  
})

function saveValue(e) {
  var name = e.target.name;
  var val = e.target.value;
  localStorage.setItem(name, val);
}

function getSavedValue(v) {
  if (!localStorage.getItem(v)) {
    return "";
  }
  return localStorage.getItem(v);
}
</script>

if there is a way to solve this problem please tell me. and if there is a way to do that with jquery I will be thankful to tell me that.

Upvotes: 1

Views: 1304

Answers (2)

brk
brk

Reputation: 50291

Here are couple of things. First instead of onkeyup use onblur so value will be saved in storage only when the focus is removed from the element.

Secondly use a common class inputs in this case and give separate name to each element.

Then get all the elements with same class, iterate through it and get value of name property using getAttribute. Use this value to check if there exist a key in localStorage

var nameArr = ["name"];
var inputs = [...document.getElementsByClassName('inputs')];
inputs.forEach(function(el) {
  console.log()
  el.value = getSavedValue(el.getAttribute('name'));
})

function saveValue(e) {
  var name = e.target.name;
  var val = e.target.value;
  localStorage.setItem(name, val);
}

function getSavedValue(v) {
  if (!localStorage.getItem(v)) {
    return "";
  }
  return localStorage.getItem(v);
}
<input type="text" class='inputs' name="firstName" onblur="saveValue(event)" />
<input type="text" class='inputs' name="lastName" onblur="saveValue(event)" />
<input type="text" class='inputs' name="age" onblur="saveValue(event)" />

Upvotes: 3

Flo
Flo

Reputation: 986

On your code you are passing the input object as a parameter instead of its name (or value; you choose). As localStorage only stores String key-value pairs, it won't work as you're trying to find a key that is an object.

in the forEach instead of:

el.value = getSavedValue(el);

set:

el.value = getSavedValue(el.name);

or let the "getSavedValue" function accept an object as parameter, but to access localStorage you must pass a string as the key.

Upvotes: 2

Related Questions