I am making a form where users can input their data. I\'d like for this date to be saved by use of local storage. But when i refresh the page only height and weight are stil
You are complicating your script. Try this. Working JSFIDDLE
If you are using jQuery once, do not mix it with pure javascript, like document.getElementById()
. And do not create a height
variable to store the $('#height').val()
, you can use this directly. Code is more readable.
$(document).ready(function() {
$(window).unload(saveSettings);
loadSettings();
});
function loadSettings() {
$('#height').val(localStorage.height);
$('#weight').val(localStorage.weight);
$('#dateOfBirth').val(localStorage.dateOfBirth);
$('input[value="' + localStorage.gender + '"]').prop('checked', true);
$("#sportive").val(localStorage.sportive);
}
function saveSettings() {
localStorage.height = $('#height').val();
localStorage.weight = $('#weight').val();
localStorage.dateOfBirth = $('#dateOfBirth').val();
localStorage.sportive = $("#sportive").val();
localStorage.gender = $('input[type=radio]:checked').val();
}
Update: If you are using jQuery 3, unload will throw an error. You should use this instead:
$(window).on('unload', function(){
saveSettings();
loadSettings();
});