Last active
August 29, 2015 13:57
-
-
Save Tom32i/9392068 to your computer and use it in GitHub Desktop.
Simple Select choice filtering system
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Choice | |
* | |
* @param {Sring} id | |
*/ | |
function Choice(id) | |
{ | |
this.element = $(document.getElementById(id)); | |
this.choices = []; | |
var children = this.element.children(), | |
length = children.length; | |
for (var i = 0; i < length; i++) { | |
var child = $(children[i]), | |
value = child.val(); | |
if (value !== null && value !== "") { | |
this.choices.push(new Option(child, this)); | |
} | |
} | |
} | |
/** | |
* Update the choice from filters | |
*/ | |
Choice.prototype.update = function(filters) | |
{ | |
var length = this.choices.length; | |
for (var i = 0; i < length; i++) { | |
this.choices[i].filter(filters); | |
} | |
}; | |
/** | |
* Option | |
* | |
* @param {Element} element | |
*/ | |
function Option(element, parent) | |
{ | |
this.element = $(element); | |
this.parent = parent; | |
this.value = this.element.val(); | |
} | |
/** | |
* Filter the option | |
* | |
* @param {Array} filters | |
*/ | |
Option.prototype.filter = function(filters) | |
{ | |
this.detach(); | |
if (this.match(filters)) { | |
this.attach(); | |
} else if(this.element.is(':selected')) { | |
this.element.prop("selected", false); | |
this.parent.element.trigger('change'); | |
} | |
}; | |
/** | |
* Filter | |
* | |
* @param {Array} filters | |
* | |
* @return {Boolean} | |
*/ | |
Option.prototype.match = function(filters) | |
{ | |
return filters.indexOf(this.value) >= 0; | |
}; | |
/** | |
* Attach to the DOM | |
*/ | |
Option.prototype.attach = function() | |
{ | |
if (!this.element.parent().length) { | |
this.parent.element.append(this.element); | |
} | |
}; | |
/** | |
* Attach to the DOM | |
*/ | |
Option.prototype.detach = function() | |
{ | |
if (this.element.parent().length) { | |
this.element.remove(); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment