5

I'm trying to store via local storage all form field values (under the input id) like so localStorage.setItem("input id", fieldvalue); when a user clicks the "save" button. the reason being is so at a later date the user has the option of reloading the form field values instead of retyping everything the problem is the input id and name fields are not known because they are generated depending on what the user selects in the previous page (what template they choose).

Demo (let's say this was generated):

<input type="text" id="meta_title" name="seo_meta_title"> 
<input type="text" id="meta_description" name="seo_meta_description"> 
<input type="text" id="header" name="header"> 

<!-- Submit form-->
  <input type="submit" value="Create">

<!-- buttons-->
  <button onclick="save()">save</button>
  <button onclick="load()">load</button>

because I don't know the input ids, I can't just write:

function save() {
  if (typeof(Storage) != "undefined") {

    //some_code_to_insert_value = x, y, z 

    localStorage.setItem("meta_title", x);
    localStorage.setItem("meta_description", y);
    localStorage.setItem("header", z);
   }
}

And same goes for the load function

// LOAD
function load() {
if (typeof(Storage) != "undefined") {
   // Adds data back into form fields 

   document.getElementById("meta_title").value = localStorage.getItem("meta_title");
   document.getElementById("meta_description").value = localStorage.getItem("meta_description");
   document.getElementById("header").value = localStorage.getItem("header");

    }
}

I'm very new to JavaScript as I'm sure you can tell any help, code or links would be much appreciated and a working js fiddle would be beyond amazing (as long as it doesn't rely on pre-knowing the input id etc..) I have spent a few hours trying to do this and wasted even more time trying to generate the JS needed with PHP in till I was told this was a terrible way to do it.

3
  • 2
    You have illegal characters in both your HTML and JavaScript. Commented Dec 3, 2014 at 13:55
  • Typo here (""meta_description") two quotes before item name. Commented Dec 3, 2014 at 13:55
  • Sorry will correct and that is just demo code is doesn't work. only there for example Commented Dec 3, 2014 at 13:57

3 Answers 3

22

If you want to rely on jQuery this can help you:

$('#save').on('click', function(){

    $('input[type="text"]').each(function(){    
        var id = $(this).attr('id');
        var value = $(this).val();
       localStorage.setItem(id, value);

    });   
});

$('#load').on('click', function(){
    $('input[type="text"]').each(function(){    
        var id = $(this).attr('id');
        var value = localStorage.getItem(id);

        $(this).val(value);

    }); 
});

I would recommend to avoid inline-js, so I updated to code to use .on() for attaching the click-handler to the two buttons.

Demo

Reference:

.each()

Sign up to request clarification or add additional context in comments.

4 Comments

Wow thank you so much this is perfect! jQuery is 100% fine, this is exactly what i wanted! Thanks again for your time! means so much to me! will come back and upvote this once i have the 15 rep it requires!
This just saved me hours of programming variables for 200+ dynamic form fields in my app. Thanks @empiric !!!!
How could I change this code to only load it if it's id is already present in localStorage?
I'd do value && $(this).val(value);
1

Revisiting that question, year 2022. Worked on a project not so long ago where I needed just that. This is a jquery based answer.

The following works with most common single value inputs, text areas and single option selects. All changes will be saved to a localStorage variable and pushed back on page refresh.

$('input[type="checkbox"],input[type="radio"],input[type="text"],input[type="email"],input[type="number"],input[type="password"],input[type="search"],input[type="tel"],input[type="url"],textarea,select:not([multiple])').each(function (t) {
    (localStorage.getItem(`local-${$(this).prop("id")}`) || localStorage.getItem(`local-${$(this).prop("name")}`)) &&
        ($(this).is(":checkbox") ? $(this).prop("checked", !0) : $(this).is(":radio") ? $(`#${localStorage.getItem(`local-${$(this).prop("name")}`)}`).prop("checked", !0) : $(this).val(localStorage.getItem(`local-${$(this).prop("id")}`))),
        $(this).on("click keyup keypress change focus", function () {
            $(this).is(":checkbox")
                ? $(this).prop("checked")
                    ? localStorage.setItem(`local-${$(this).prop("id")}`, $(this).val())
                    : localStorage.removeItem(`local-${$(this).prop("id")}`)
                : $(this).is(":radio")
                ? $(this).prop("checked") && localStorage.setItem(`local-${$(this).prop("name")}`, $(this).prop("id"))
                : localStorage.setItem(`local-${$(this).prop("id")}`, $(this).val());
        });
});

Comments

0
   Replace Html Code And Script File 
   <form method='post' id='myform'>
    <input type="text" id="meta_title" name="seo_meta_title"> 
    <input type="text" id="meta_description" name="seo_meta_description"> 
    <input type="text" id="header" name="header"> 

    <!-- Submit form-->
      <input type="submit" id="save" value="Create">

    <!-- buttons-->
      <button onclick="save()">save</button>
      <button onclick="load()">load</button>
    </form>
    <script>
    $('#save').on('click', function(){
       var post_vars = $('#myform').serializeArray();
       localStorage.setItem(id, post_vars);
    });
    </script>

Comments

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.