HTML5 Game - Storing Forms with Local Storage

Description

Storing Forms with Local Storage

Demo

ResultView the demo in separate window

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8" />
    <title>Storing Form Data with Local Storage</title>
    <script>
        function checkStorage() {
            if (window.localStorage) {//w ww  . j  a va 2 s  .  c o  m
                let key, value, field;
                for (let i = 0; i < localStorage.length; i++) {
                    key = localStorage.key(i);
                    field = document.getElementById(key);
                    if (field) {
                        value = unescape(localStorage.getItem(key));
                        field.value = value;
                    }
                }
            }
        }
        function changeField(formField) {
            if (window.localStorage) {
                let key, value;
                key = formField.id;
                value = escape(formField.value);
                try {
                    localStorage.setItem(key, value);
                } catch (err) {
                    if (err.code == QUOTA_EXCEEDED_ERR) {
                        alert('localStorage ran out of memory.');
                    }
                }
            } else {
                alert('localStorage is not supported.');
            }
        }
        window.addEventListener('load', checkStorage, false);
    </script>
</head>

<body>
    <h1>My Form</h1>
    <form id='myForm'>
        <table>
            <tr>
                <td>First Name:</td>
                <td><input type="text" id="firstName" onchange="changeField(this);" /></td>
            </tr>
            <tr>
                <td>Last Name:</td>
                <td><input type="text" id="lastName" onchange="changeField(this);" /></td>
            </tr>
            <tr>
                <td>Email:</td>
                <td><input type="email" id="email" onchange="changeField(this);" /></td>
            </tr>
            <tr>
                <td>Telephone:</td>
                <td><input type="tel" id="phone" onchange="changeField(this);" /></td>
            </tr>
        </table>
    </form>
</body>

</html>

Related Topic