I have function which stores username and password in local storage once the remember me check box is clicked. So far it works fine, but the function only works when user enter his/her username and password in the input fields and then click on remember me check box.
So in short there are 2 cases:
1) Enter username and password -> click remember me check box -> submit form (works fine)
2) Click remember me check box -> Enter username and password -> submit form (Not working - Blank fields are displayed.)
How can I modify my function and make sure that if the user clicks on remember me check box first and then enter username and password the fields are populated on page refresh or when the user comes back to the website again.
This is my function looks like:
$(function() {
if (localStorage.checkBoxValidation && localStorage.checkBoxValidation != '') {
$('#rememberMe').attr('checked', 'checked');
$('#loginEmail').val(localStorage.userName);
$('#password').val(localStorage.password);
} else {
$('#rememberMe').removeAttr('checked');
$('#loginEmail').val('');
$('#password').val('');
}
$('#rememberMe').click(function() {
if ($('#rememberMe').is(':checked')) {
// save username and password
localStorage.userName = $('#loginEmail').val();
localStorage.password = $('#password').val();
localStorage.checkBoxValidation = $('#rememberMe').val();
} else {
localStorage.userName = '';
localStorage.password = '';
localStorage.checkBoxValidation = '';
}
});
});
You shouldn't listen to the click events of specific form elements but rather to the submit event of the form.
When the form is submitted, you have the information from all fields at hand and the order in which the user fills in the form fields doesn't matter.
$('#my-form').on('submit', function() {
/* place your logic here… */
});
Store the data on form submit function
$('#urformid').on('submit', function() {
if ($('#rememberMe').is(':checked')) {
// save username and password
localStorage.userName = $('#loginEmail').val();
localStorage.password = $('#password').val();
localStorage.checkBoxValidation = $('#rememberMe').val();
} else {
localStorage.userName = '';
localStorage.password = '';
localStorage.checkBoxValidation = '';
}
//Other form functions
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With