JQuery Forms Prepopulate Input with KeyUp and Change

From CoderLearner
Jump to: navigation, search

Description

You want to pre-populate the input from one field to the other field based on the checkbox. This can be useful when you have the current address and the home address to be entered by the user. If both addresses are the same, the user do not need to require to re-typing.

Example 1

<!DOCTYPE html>
<html>
    <head>
        <title>Use Keyup and Change For Input form</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script type="text/javascript" src="jquery.min.js"></script>
        <script>
            $().ready(function() {
                $('#current_address input:text').bind('keyup change', function() {
                    if ($('#ch_same:checked').length) {
                        // find index both input must have the same number of input field
                        var index = $('#current_address input:text').index(this);
                        // value
                        var value = $(this).val();
                        $('#home_address input:text:eq(' + index + ')').val(value);
                    }
                });
            });
        </script>
    </head>
    <body>
        <h3>Register</h3>
        <form action="#" method="post" name="frm-test">

            <fieldset id="current_address">
                <legend>Current Address</legend>
                <label for="ca_city">City</label>
                <input type="text" id="ca_city" name="ca_city"/>
                <label for="ca_country">Country</label>
                <input type="text" id="ca_country" name="ca_country"/>
            </fieldset>
            <label for="ch_same">Current and Home Address are the same</label>
            <input type="checkbox" name="ch_same" id="ch_same" value="The Same"/>
            <fieldset id="home_address">
                <legend>Home Address</legend>
                <label for="ha_city">City</label>
                <input type="text" id="ha_city" name="ha_city"/>
                <label for="ca_country">Country</label>
                <input type="text" id="ha_country" name="ha_country"/>
            </fieldset>

            <input type="submit" name="btn_SAVE" value="Save"/>

        </form>
    </body>
</html>