I have a huge form with a lot of inputs, textareas, and checkboxes. The form has a captcha on it. I want to save the form answers locally with localStorage
so that if the captcha returns fail
, their form data will be repopulated.
HTML
<form name="wellnessForm" id="wellnessForm" action="confirm.php" method="POST">
<input type="text" name="firstName" />
<br/>
<input type="checkbox" name="noConcernsChk[]" value="1" />
<input type="checkbox" name="noConcernsChk[]" value="2" />
<br/>
<textarea>
</textarea>
</form>
jQuery
// DOM ready
$(function(){
$(':text').blur(function(e){
localStorage.setItem("flag", "set");
var data = $('#wellnessForm').serializeArray();
$.each(data, function(i, obj){
localStorage.setItem(obj.name, obj.value);
});
});
$(':checkbox').click(function(e){
localStorage.setItem("flag", "set");
var data = $('#wellnessForm').serializeArray();
$.each(data, function(i, obj){
localStorage.setItem(obj.value, e.checked);
});
});
// test if there is already saved data
if( localStorage.getItem("flag") == "set" ){
var data = $("#wellnessForm").serializeArray();
// have to select the valid inputs based on their name attribute
$.each(data, function(i, obj){
// check if checkbox
if(obj.name == 'noConcernsChk[]'){
$( "[value='"+obj.value+"']:checkbox" ).prop('checked', true);
}
else{
$("[name='" + obj.name + "']").val(localStorage.getItem(obj.name));
}
});
}
// provide mechanism to remove data (TODO: remove actual data not just kill the flag)
$("#clearData").click(function(e){
e.preventDefault();
localStorage.setItem("flag", "");
});
});
How far I got
As you can see by my example, I have text inputs working. However I'm stuck on checkboxes. I would like to have the localStorage
remember if the boxes were checked or not, and if they were, re-check them in the form for the user. I also haven't gotten textarea working yet but that shouldn't be too hard.
Question
How can you store checkbox state to local storage, and then recall it (and have the proper boxes checked)?