2
* @author <a href="mailto:keith.hughitt@nasa.gov">Keith Hughitt</a>
3
* @fileOverview Contains the definition for a Hierarchical or "Tree Select" class which links
4
* several select form elements together based off a given tree structure such changes at any level automatically
5
* determine valid options for select items at lower levels.
7
/*jslint browser: true, evil: true, white: true, onevar: true, undef: true, nomen: false, eqeqeq: true, plusplus: true,
8
bitwise: true, regexp: true, strict: true, forin: true, newcap: true, immed: true, maxlen: 120, sub: true */
9
/*global Class, $, window */
11
var TreeSelect = Class.extend(
12
/** @lends TreeSelect.prototype */
19
init: function (selectIds, tree, initialChoices, callback) {
20
this.selectIds = selectIds;
22
this.height = selectIds.length;
23
this.callback = callback;
24
this.selected = initialChoices;
26
this._initSelectMenus();
28
this._setupEventHandlers();
32
* @description Populates SELECT menus and selects initial choices
34
_initSelectMenus: function () {
37
this._updateSelectMenus();
39
// Set initial choices in select menus
40
$.each(this.selectIds, function (depth, id) {
41
$(id + " > option").each(function (index, option) {
42
if (option.value === self.selected[depth]) {
43
$(id).attr("selectedIndex", index);
50
* @description Update the list of selected options
51
* @param {Object} depth
52
* @param {Object} newChoice
54
_updateSelected: function (depth, newChoice) {
55
var nav, getFirstItem, i, self = this;
57
this.selected[depth] = newChoice;
59
// Function to get the first item in an array
60
getFirstItem = function (arr) {
61
for (var item in arr) {
66
// For each item below the selected parameter, use first available value
68
for (i = 0; i < this.height; i += 1) {
70
this.selected[i] = getFirstItem(eval(nav));
72
nav += '["' + this.selected[i] + '"]';
75
this._updateSelectMenus(depth + 1);
79
* @description Updates the SELECT menus to show valid choices at
80
* each level based on chosen values from above levels.
81
* @param {Object} startDepth
83
_updateSelectMenus: function (startDepth) {
84
var select, i, nav, opt, self = this;
86
if (typeof(startDepth) === "undefined") {
90
$.each(this.selectIds, function (depth, id) {
91
if (depth >= startDepth) {
98
// navigate to current depth
100
for (i = 0; i < depth; i += 1) {
101
nav += '["' + self.selected[i] + '"]';
105
for (var choice in eval(nav)) {
106
opt = $("<option value='" + choice + "'>" + choice + "</option>");
114
* @description Returns the value associated with the currently selected leaf-node
116
_value: function () {
117
var nav, self = this;
120
$.each(this.selected, function (i, choice) {
121
nav += '["' + choice + '"]';
128
* @description Sets up event-handlers for each form field
130
_setupEventHandlers: function () {
133
$.each(this.selectIds, function (i, id) {
134
$(id).change(function (e) {
135
self._updateSelected(i, this.value);
136
self.callback(self._value());