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