Как сохранить значение input в localStorage

Есть задача запомнить путем записи в local storage введенное значение в input с атрибутами name="adress" и class="t-input js-tilda-rule".

Подскажите как реализовать?


Ответы (1 шт):

Автор решения: OPTIMUS PRIME

См. → CSS селекторы

<input name="adress" class="t-input js-tilda-rule">

$(function() {
  let $input = $('[name="adress"].t-input.js-tilda-rule');

  if ($input.length) {
    $input.val( localStorage.getItem("example-name-adress") || "" );

    $input.on('input', function() {
      localStorage.setItem("example-name-adress", $(this).val() );
    });
  }
});

↑ или без jQ ↓

document.addEventListener('DOMContentLoaded', function() {
  let input = document.querySelector('[name="adress"].t-input.js-tilda-rule');

  if (input) {
    input.value = localStorage.getItem("example-name-adress") || "";

    input.addEventListener('input', function() {
      localStorage.setItem("example-name-adress", this.value);
    });
  }
});
→ Ссылка