Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 localstorage remember me in login box

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 = '';
        }
    });
});
like image 663
zaq Avatar asked Oct 19 '25 23:10

zaq


2 Answers

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… */
});
like image 107
feeela Avatar answered Oct 21 '25 13:10

feeela


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
});
like image 31
Sridhar R Avatar answered Oct 21 '25 14:10

Sridhar R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!