0

I have a form where I save the data in a cookie with localStorage. This all works fine, but If clear (just deleting with backspace) the value of an input field or textarea so that the placeholder text shows up again and I refresh or come back at the page, the input field and textarea shows 'undefined' in the fields instead of the placeholder text. How do I get rid of 'undefined'?

I made a demo form in a pen, so you can see and experience what I'm talking about.
http://codepen.io/gentlemedia/full/VevPyP/

The HTML of the demo form :

<form>

    <div>
        <input type="email" name="email" class="stored" placeholder="email address" required aria-required="true" />
    </div>   
    <div>
        <select name="gender" class="stored" required aria-required="true">
            <option valsue="">gender</option>
            <option value="male">male</option>
            <option value="female">female</option>
        </select>
    </div>
    <div>
        <textarea name="bio" class="stored" placeholder="a little bit about yourself" required aria-required="true"></textarea>
    </div>

</form>

The jQuery/localStorage to save and return the data:

$(function() {

    $.each($('.stored'), function() {
        if(localStorage[$(this).attr('name')]) {
          $(this).val(localStorage[$(this).attr('name')]);
        }
    });

});

$('.stored').change(function() {
    localStorage[$(this).attr('name')] = $(this).val() || $(this).find('option:selected').val();
});

Edited by gentlemedia: typos

1
Contributor
2
Replies
19
Views
1 Year
Discussion Span
Last Post by gentlemedia
0

I've kind of fixed it by not combining the input/textarea and select in one .change() function.

I keep them now seperate like this with the .stored class only on the input and textarea fields:

$('.stored').on('keyup focusout', function() {
    localStorage[$(this).attr('name')] = $(this).val();
});

$('select').on('change', function() {
    localStorage[$(this).attr('name')] = $(this).find('option:selected').val();
});

I keep the thread open, because perhaps I have an error in my first approach that I don't see for some reason.

Edited by gentlemedia

1

It's solved. Not sure what I was thinking by using || instead of just the, to combine them.

$('.stored').change(function() {
    localStorage[$(this).attr('name')] = $(this).val(), $(this).find('option:selected').val();
});

Edited by gentlemedia

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.