static/js/forms.js
author Tero Marttila <terom@fixme.fi>
Wed, 22 Dec 2010 02:52:25 +0200
changeset 6 72c73df76db2
child 9 0327b83959e9
permissions -rw-r--r--
Split wsgi.py into controllers/customers/urls for now; start orders form
/**
 * jQuery support code for our forms
 */

(function($) {
    /*
     * When non-zero <select>/<option> is selected, apply that option as pre-filled values for other form items
     */
    $.fn.formSelectPreset = function (opts) {
        opts = $.extend({
            // which option value is the "default", i.e. 'create new'
            valueDefault: 0,

            // which element to apply selected option value (id) to
            valueTarget: null,

            // which element to apply selected option text to
            textTarget: null,
        }, opts);

        this.change(function (event) {
            // selected option value (i.e. id)
            value = $(this).val();

            // selected option text (i.e. title/name)
            text = $.trim($(this).find("option:selected").text());

            // fields to set
            field_values = [
                [ opts.valueTarget, value ],
                [ opts.textTarget, text ]
            ];

            if (value == opts.valueDefault) {
                // clear and re-enable fields
                if (opts.valueTarget) {
                    opts.valueTarget.removeAttr('disabled');
                    opts.valueTarget.val("");
                }

                if (opts.textTarget) {
                    opts.textTarget.removeAttr('disabled');
                    opts.textTarget.val("");
                }

                return;
            }

            // set field values
            if (opts.valueTarget) {
                opts.valueTarget.attr('disabled', "disabled");
                opts.valueTarget.val(value);
            }

            if (opts.textTarget) {
                opts.textTarget.attr('disabled', "disabled");
                opts.textTarget.val(text);
            }
        });
    }
})(jQuery);