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();
});

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.

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();
});
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.