/** * @requires $ jQuery * @requires _ UnderscoreJS */ (function(ns) { "use strict"; /** * @alias lib.form.element.SelectOther * @constructor */ ns.SelectOther = function () { this.construct.apply(this, arguments); }; var fn = ns.SelectOther.prototype; fn.construct = function (options) { this.ns = 'feso'; this.textElement = $('#' + options.id); this.selectElement = $('#' + options.selectId); this.parentElement = $('#' + options.parentElementId); if (!this.textElement.length || !this.selectElement.length) { throw Error('SelectOther element initialization failed'); } this.hasOtherInput = options.hasOtherInput; this.OTHER = options.OTHER; this.selectElement.on('change.' + this.ns, _.bind(this.selectElementOnChange, this)); if (this.parentElement.length) { this.parentElement.on('change.' + this.ns, _.bind(this.parentElementOnChange , this)); this.queryUrl = options.queryUrl; } }; fn.selectElementOnChange = function (event) { if (!this.hasOtherInput) { this.textElement.val(this.selectElement.val()); return; } $('#' + this.textElement.prop('id') + '-element').toggleClass(this.OTHER, this.selectElement.val() == this.OTHER); if (this.selectElement.val() == this.OTHER) { this.textElement.show(); if (!event.isTrigger) { this.textElement.val('').focus(); } } else { this.textElement.val(this.selectElement.val()).hide(); } }; fn.parentElementOnChange = function (event) { if (this.parentElement.val() == '') { this.setSelectOptions([]); } else { var request = {}; request[this.parentElement.attr('name')] = this.parentElement.val(); qs.ajax(this.queryUrl, request, {type: 'get'}).done(_.bind(this.onLoadOptions, this)); } }; fn.setSelectOptions = function (options) { var oldValue = this.selectElement.val(); var otherTitle = this.selectElement.find('option[value="' + this.OTHER + '"]').text(); var emptyTitle = this.selectElement.find('option[value=""]').text(); if (this.hasOtherInput) { options.push({title: otherTitle, value : this.OTHER}); } qs.form.select.setOptions(this.selectElement.get(0), options, emptyTitle); this.selectElement.val(oldValue); // Save old value as "other" value when parent element is changed and select element doesn't have such option if (this.hasOtherInput && this.selectElement.val() != oldValue) { this.selectElement.val(this.OTHER); this.textElement.val(oldValue); } this.selectElement.trigger('change.' + this.ns); }; fn.onLoadOptions = function (options) { this.setSelectOptions(options); }; })(qs.defineNS('lib.form.element'));