1

Есть 3 инпута, надо сохранить их значения в localStorage. Все три поля не может сохранить почему-то:

var txt = document.getElementById("1");
txt.value = localStorage["1"] || "";
window.go = function() {
  localStorage["1"] = txt.value;
}
var txt = document.getElementById("2");
txt.value = localStorage["2"] || "";
window.go = function() {
  localStorage["2"] = txt.value;
}
var txt = document.getElementById("3");
txt.value = localStorage["3"] || "";
window.go = function() {
  localStorage["3"] = txt.value;
}
<input id="1">
<input id="2">
<input id="3">

1 ответ 1

2
  1. Сохранение и получение значений из localStorage реализуется с помощью методов setItem и getItem
  2. Сохранять значения input-ов имеет смысл при их изменении, то есть при срабатывании события change

Пример реализации:

document.addEventListener("DOMContentLoaded", function() {
  var ids = ["1", "2", "3"];
  for (var id of ids) {
    var input = document.getElementById(id);
    input.value = localStorage.getItem(id);
    (function(id, input) {
      input.addEventListener("change", function() {
        localStorage.setItem(id, input.value);
      });
    })(id, input);
  } 
});

Полный пример в JSFiddle

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.