Skip to content

Instantly share code, notes, and snippets.

@Tom32i
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tom32i/9392068 to your computer and use it in GitHub Desktop.
Save Tom32i/9392068 to your computer and use it in GitHub Desktop.
Simple Select choice filtering system
/**
* 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