jStorage-form remember username

Demo 2

by JSDavi

HTML

<script src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.1.0/prototype.js"></script>
<script src="https://raw.githubusercontent.com/andris9/jStorage/master/jstorage.js"></script>
<form id="form" class="form-horizontal" method="post">
    <!--action="index.html"-->
    <fieldset>
        <div class="input-prepend" title="用户名" data-rel="tooltip"> <span class="add-on" style="width:28px"><i class="icon-user"></i></span>

            <input autofocus class="input-large span10" name="username" id="username" type="text" />
            <!--value="admin"-->
        </div>
        <div class="clearfix"></div>
        <br>
        <div class="input-prepend" title="密码" data-rel="tooltip"> <span class="add-on" style="width:28px"><i class="icon-lock"></i></span>

            <input class="input-large span10" name="password" id="password" type="password" />
            <!--value="admin123456"-->
        </div>
        <div class="clearfix"></div>
        <br>
        <div class="input-prepend">
            <label class="remember" for="remember">
                <div class="checker" id="uniform-remember">
                    <input type="checkbox" id="remember" style="opacity: 1; ">记住我</div>
            </label>
        </div>
        <div class="clearfix"></div>
        <br>
        <p class="center">
            <button type="submit" class="btn btn-primary span4 center" onclick="checkLogin()">登陆</button>
        </p>
    </fieldset>
</form>

JavaScript

// start this when DOM is ready
$(function () {
    var checkbox = $('#remember'),
        userField = $('#username'),

        // assign the key name to a variable
        // so we don't have to type it up every time
        key = 'savedUsername',

        // use jStorage to retrieve a stored key
        // on first load this is going to return undefined
        username = $.jStorage.get(key);

    // if a username was saved from previous session
    // set the value of the username field to that
    // tick off the checkbox and set focus on password field
    if (username) {
        userField.val(username);
        checkbox.prop('checked', true);
        $('#password').focus();
    }

    // if username wasn't saved then
    // set username field value to blank and focus on it
    // and make sure the checkbox is unchecked
    else {
        userField.val('').focus();
        checkbox.prop('checked', false);
    }

    // when form is submitted check the checkbox
    // if it's checked then save the username using jStorage
    // if not then delete whatever saved username exists
    $('#form').submit(function (e) {
        if (checkbox.prop('checked')) {
            $.jStorage.set(key, userField.val());
        } else {
            $.jStorage.deleteKey(key);
        }
    });
});
//$.jStorage.set('savedForm', $('form').serializeArray());