Slimselect: selecting second option after searching not working - javascript

I asked this question by gitHub, but I try it here as well maybe someone knows the issue.
I am using slim select plugin, when I try to select the second option after searching I get an error
see picture:
But when I click outside so that the drop down goes closed and start searching again then I can select many options without getting the error.
Here is the code snippet where slimselect is initialized:
function initDropDowns () {
$('[slimselect]').each(function (index) {
var id = $(this).attr("id");
var placeholder = $(this).data("placeholder");
var selectByGroup = true;
var compareDropDown = false;
var dataSelectByGroup = $(this).data("selectbygroup");
var dataCmpareDropdown = $(this).data("comparedropdown");
if (dataSelectByGroup) {
selectByGroup = dataSelectByGroup === "true";
}
if (dataCmpareDropdown) {
compareDropDown = dataCmpareDropdown === "true";
}
var that = this;
var select = new SlimSelect({
select: '#' + id,
placeholder: placeholder,
showSearch: true,
searchText: settings.texts.noSearchResults,
searchPlaceholder: settings.texts.searchPlaceholder,
searchingText: settings.texts.searchingText,
searchHighlight: true,
closeOnSelect: false,
showOptionTooltips: true,
selectByGroup: selectByGroup,
hideSelectedOption:true,
limit: 5,
beforeOnChange: function (info) {
if ($(that).data('singleselect') === true) {
dropDowns[that.id].set ([]);
}
},
onChange: slimSelectOnChange
});
dropDowns[id] = select;
});
}

Related

How to change fancytree SelectMode on a button click event?

I am using the a tree view/tree grid plugin which is called fancytree (Here is the link)
I initially (when the page loads) set the selectMode to 2 which allows the users to select multiple options.
// Init
$("#Organizations .OrgTree").each(function () {
var $this = $(this);
var organizationUnitId = $this.data("orgid");
//var treeData = JSON.parse($("#treeData_" + organizationUnitId).val());
$this.fancytree({
extensions: ["persist"],
selectMode: 2,
persist: {
expandLazy: true
store: "auto" 'session': sessionStore
},
icons: false,
checkbox: true,
toggleEffect: null, //disable animations
source: window["treeData_" + organizationUnitId], // treeData
lazyLoad: function (event, data) {
var node = data.node;
data.result = {
// Some data
};
}
});
});
What I want to do is, when I click on a button, I want to change the selectMode and set it to 1 or 3.
I have tried to read through the documentation and found this as well
But I won't work. Here is some code:
//Bind click to search button
$("#changeSelectModeBtn").click(function () {
debugger;
$("#Organizations .OrgTree").fancytree("getTree").visit(function (node) {
node.setSelected(false);
});
$("#Organizations .OrgTree").fancytree({ selectMode: 3 });
var selectedKeys = [];
$("#Organizations .OrgTree").each(function () {
var $this = $(this);
var orgTree = $(this).fancytree("getTree");
var selectedParentNodes = orgTree.getSelectedNodes();
for (node in selectedParentNodes) {
selectedKeys.push(selectedParentNodes[node].key)
}
// Save orgtree in hidden fields
var organizationUnitId = $this.data("orgid");
var treeData = orgTree.toDict(true);
window["treeData_" + organizationUnitId] = treeData.children; //$("#treeData_" + organizationUnitId).val(JSON.stringify(treeData.children))
});
if (selectedKeys) {
$("#HiddenOrganizationUnitIds").val(selectedKeys.join(","));
}
})
Can someone please help me?
Thanks in advance!
All options can be set dynamically using the jQuery widget pattern.
For example, you can use
$("#tree").fancytree("option", "selectMode", 3);
See also https://github.com/mar10/fancytree/wiki#configure-options

Transforming old code to ember component

currently i'm starting with Ember, and i'm loving it! I'm with some difficulties, especially when it comes to components.
For you to understand, I'm going through old code to Ember, and I would like to turn this code into a Component, but I do not know actually how to start, since I do not know how to catch the button being clicked, and I also realized that Ember has several helpers, maybe I do not need any of this giant code to do what I want.
This is the old code result: http://codepen.io/anon/pen/WQjobV?editors=110
var eventObj = {};
var eventInstances = {};
var actual;
var others;
var clicked;
var createEventInstance = function (obj) {
for (var key in obj) {
eventInstances[key] = new Event(obj[key]);
}
};
var returnStyle = function (inCommon) {
var $inCommon = inCommon;
$inCommon.css({
width: '342.4px',
minWidth: '342.4px'
});
$inCommon.find('.cta').removeClass('hidden');
$inCommon.find('.event-close').removeClass('inline');
$inCommon.find('.event-info_list').removeClass('inline');
$inCommon.removeClass('hidden');
$inCommon.find('.expanded').slideUp();
$inCommon.find('.expanded').slideUp();
$inCommon.find('.event-arrow').remove();
$inCommon.find('h2').find('ul').remove('ul');
};
var Event = function (id) {
this.id = id;
};
Event.prototype.expandForm = function () {
actual.css('width', '100%');
actual.find('.event-info_list').addClass('inline');
actual.find('.expanded').slideDown().css('display', 'block');
actual.find('.event-close').addClass('inline');
};
Event.prototype.close = function () {
returnStyle(actual);
returnStyle(others);
};
Event.prototype.hideElements = function () {
clicked.addClass('hidden');
others.addClass('hidden');
};
Event.prototype.maskPhone = function () {
$('[name$=phone]').mask('(99) 99999-9999', {
placeholder: '(00) 0000-0000'
});
};
$('.submit-form').on('click', function (e) {
e.preventDefault();
var id = '.' + $(this).data('id');
var name = $(id).children('#person-name').val();
var email = $(id).children('#person-email').val();
var guests = $(id).children('#person-obs.guests').val();
var phone = $(id).children('#person-phone').val();
var participants = $(id).children('#booking-participants').val();
if (name === '' || email === '' || phone === '' || participants === '' || guests === '') {
alert('Preencha os campos obrigatórios.');
} else {
$(id).submit();
}
});
Event.prototype.createDropDown = function () {
actual.find('h2').addClass('event-change')
.append('<span class="event-arrow" aria-hidden="true">â–¼</span>')
.append(function () {
var self = $(this);
var list = '<ul class="dropdown hidden">';
$('.event').each(function (index) {
if ($(this).find('h2')[0] != self[0]) {
list += '<li data-index="' + index + '">' + $(this).find('h2').text() + '</li>';
}
});
return list;
}).click(function () {
if ($(this).attr('data-expanded') == true) {
$(this).find('ul').toggleClass('hidden');
$(this).attr('data-expanded', false);
} else {
$(this).find('ul').toggleClass('hidden');
$(this).attr('data-expanded', true);
}
}).find('li').click(function (e) {
e.stopPropagation();
actual.find('.event-info_list').removeClass('inline');
actual.find('h2').attr('data-expanded', false);
actual.find('h2').removeClass('event-change');
actual.find('.expanded').slideUp().css('display', 'inline-block');
others.removeClass('hidden');
actual.find('.cta').removeClass('hidden');
actual.find('h2').find('.event-arrow').remove();
actual.find('h2').off('click');
actual.find('h2').find('ul').remove('ul');
$($('.event')[$(this).attr('data-index')]).find('.cta').trigger('click');
});
};
Event.prototype.open = function () {
actual = $('[data-id="' + this.id + '"]');
others = $('.event').not(actual);
clicked = actual.find('.cta');
this.hideElements();
this.expandForm();
this.createDropDown();
this.maskPhone();
};
$('.event').each(function (i, event) {
var prop = 'id' + $(event).data('id');
var value = $(event).data('id');
eventObj[prop] = value;
});
createEventInstance(eventObj);
Basically i have this boxes, which box represent one booking in some event (will be populate by the server). When the user clicks in one box, this boxes expands and the other disappear. But than a dropbox will be created with the other boxes, so the user can navigate in the events by this dropdown.
I didn't do much with Ember, i transform the "events" div into a component with the name "BookingBoxComponent" and two actions:
SiteApp.BookingBoxComponent = Ember.Component.extend({
actions:
open: function() {
// HOW COULD I ACCESS THE CLICKED BUTTON HERE?
},
close: function() {
}
});
As you can see, i put two actions, one for opening the box and other for closing, should i just put the logic in both, or i can improve this like a Ember way?
I don't know if i am asking to much here, so if i am, at least i would like to know how to access the button clicked in the open method, i was trying passing as a parameter, like:
<button {{action 'open' this}}></button>
But didn't work.
I could offer 50 of my points to someone who help transform the old cold in a Ember way code.
Thanks.
The event object will be passed with every action as the last parameter, so when you specified this you were actually passing whatever object has context in that block. In your open function, do not pass this and do
open: function(event) {
// event.currentTarget would be the button
}
And now you can do something like event.currentTarget or event.target

ComboBox that shows a tree in the dropdown

I want to write a ComboBox which lets the user type in a query and at the same time lets him select a value from a tree. I have tried writing a tree-select but if I change the code to inherit from dijit.form.ComboBox instead of a dijit.form.Select, the code breaks.
Here is what I had tree for tree select:
dojo.declare('TreeSelect',dijit.form.Select,{
constructor: function(widgetArgs){
this.tree = widgetArgs.tree || new FC_Tree();
this.initTree = widgetArgs.initTree;
if(dojo.isFunction(this.initTree))
this.initTree();
},
postCreate: function(){
this.inherited(arguments);
this.option = {label: '', value: 'NoValue'};
this.tree.option = this.option;
this.addOption(this.option);
dojo.connect(this.tree,'onClick',this,'closeDropDown');
dojo.connect(this.tree,'itemSelected',this,'selectOption');
},
selectOption: function(opt){
this.option.label = opt.label || opt;
this.option.value = opt.value || opt;
this.option.id = opt.id || opt;
this.set('value',this.option);
},
_getMenuItemForOption: function (option){
return this.tree;
},
openDropDown: function(){
this.tree.refresh();
this.inherited(arguments);
},
clear: function(){
this.tree.clear();
this.tree.option.value = '';
this.tree.option.label = '';
this.tree.option.id = '';
this.set('value',this.tree.option);
},
initializeTree: function(treeData) {
// Init the tree only if needed
dojo.forEach(treeData, function(field) {
var store = this.tree.model.store;
store.newItem(field);
}, this);
},
setOpenCallback: function(callback){
this.tree.setOpenCallback(callback);
},
resetTree: function() {
var store = this.tree.model.store;
store.fetch( { query: { id: "*" },
onItem: function(item) {
store.deleteItem(item);
}
});
}
});
I had tried replacing the code for combobox like this:
dojo.declare('TreeSelect',dijit.form.ComboBox,{
Please help me rectify it.
Thanks in advance!
Adding the code for FC_Tree:
dojo.declare('FC_Tree',dijit.Tree,{
showRoot: false,
openOnClick: true,
noIconForNode: true,
noMarginForNode: true,
persist: false,
openCallback: null,
constructor: function(){
if(dojo.isUndefined(arguments[0]) || dojo.isUndefined(arguments[0].model))
{
var forest_store = new FC_DataStore({id: 'id', label: 'label'});
this._storeloaded = false;
dojo.connect(forest_store,'loaded',this,function(){this._storeloaded = true;})
this.model = new dijit.tree.ForestStoreModel({store:forest_store});
}
},
setOpenCallback: function(callback){
this.openCallback = callback;
},
option: {},
itemSelected: function(item){
},
onClick: function(item, node, evt){
var store = this.model.store;
get = function(){
return store.getValue(item, "isDir");
};
// on folder click mark it unselectable
if(get("isDir"))
{
this.isExpanded = true;
this.isExpandable = true;
}
else
{ //In case the item has 'onClick' delegate execute it and assign the output to 'selItem'
var selItem = (item.onClick && item.onClick[0])? item.onClick[0](this.model.store,item.parentID[0]):item.id[0];
this.option.id = item.id;
this.option.value = item.value;
this.option.label = item.label;
this.itemSelected(this.option);
}
},
onOpen: function(item, node){
if(this.rootNode.item == item){
return this.inherited(arguments);
}
var data = (this.openCallback != null) ? this.openCallback(item, node) : {};
if(!data.length){
return this.inherited(arguments);
}
FC_Comm.when(data,{
onCmdSuccess: dojo.hitch(this,function(data){
var store = this.model.store;
var children = store.getValues(item, 'children');
dojo.forEach(children, function(child) {
// don't delete child if doNotDelete flag is true
if(!store.getValue(child, "doNotDelete"))
store.deleteItem(child);
});
if (data) {
var store = this.model.store;
if (store) {
dojo.forEach(data, function(child) {
store.newItem(child, {parent : item, attribute: 'children'});
});
}
}
})
});
},
refresh: function(){
if(this._storeloaded){
// Close the store (So that the store will do a new fetch()).
this.model.store.clearOnClose = true;
this.model.store.close();
// Completely delete every node from the dijit.Tree
this._itemNodesMap = {};
this.rootNode.state = "UNCHECKED";
this.model.root.children = null;
// Destroy the widget
this.rootNode.destroyRecursive();
// Recreate the model, (with the model again)
this.model.constructor(this.model)
// Rebuild the tree
this.postMixInProperties();
this._load();
this._storeloaded = false;
}
},
clear: function(){
this.model.store.load([]);
}
});
Possibly you will find inspiration / answer in this fiddle
The recursiveHunt and selectTreeNodeById functions are logic to seek out the path of an item by its id. Its quite excessive and you may find a better solution (dont know 100% what data your json is like)..
Basically, use FilteringSelect and reference the tree in this object. Also for Tree, reference the select.
Then for your tree, hook into load function (also called on refresh afaik) and in turn for the select, use onBlur to initate selecting treenode.
var combo = new dijit.form.FilteringSelect({
onBlur: function() {
// called when filter-select is 'left'
if (this.validate()) {
// only act if the value holds an actual item reference
var id = this.get("value");
var name = this.get("displayedValue");
this.tree.selectNode(id);
}
}
});
var tree = new dijit.Tree( { ....
onLoad: function() {
combostore.setData(this.model.store._arrayOfAllItems);
},
onClick: function(item) {
// uses 'this.combo', must be present
// also, we must have the same 'base store' for both combo and model
var _name = this.model.store.getValue(item, this.combo.searchAttr);
this.combo.set("item", item, false, _name);
},
selectNode: function(lookfor) {
selectTreeNodeById(this, lookfor);
},
combo: combo // <<<<<<
});
combo.tree = tree // <<<<<<
Make sure that the model has a rootId, and also that your select.searchAttr matches tree.model.labelAttr. See working sample on the fiddle

jQGrid Column Chooser Modal Overlay

Looking off this example, notice how clicking on the Search button brings up a modal form with a darkened overlay behind it. Now notice how clicking on the Column Chooser button brings up a modal form but no overlay behind it.
My question is: how do I get the dark overlay to appear behind my Column Chooser popup?
There are currently undocumented option of the columnChooser:
$(this).jqGrid('columnChooser', {modal: true});
The demo demonstrate this. One can set default parameters for the columnChooser with respect of $.jgrid.col too:
$.extend(true, $.jgrid.col, {
modal: true
});
Recently I posted the suggestion to extend a little functionality of the columnChooser, but only a part of the changes are current code of the jqGrid. Nevertheless in the new version will be possible to set much more jQuery UI Dialog options with respect of new dialog_opts option. For example the usage of the following will be possible
$(this).jqGrid('columnChooser', {
dialog_opts: {
modal: true,
minWidth: 470,
show: 'blind',
hide: 'explode'
}
});
To use full features which I suggested you can just overwrite the standard implementation of columnChooser. One can do this by including the following code
$.jgrid.extend({
columnChooser : function(opts) {
var self = this;
if($("#colchooser_"+$.jgrid.jqID(self[0].p.id)).length ) { return; }
var selector = $('<div id="colchooser_'+self[0].p.id+'" style="position:relative;overflow:hidden"><div><select multiple="multiple"></select></div></div>');
var select = $('select', selector);
function insert(perm,i,v) {
if(i>=0){
var a = perm.slice();
var b = a.splice(i,Math.max(perm.length-i,i));
if(i>perm.length) { i = perm.length; }
a[i] = v;
return a.concat(b);
}
}
opts = $.extend({
"width" : 420,
"height" : 240,
"classname" : null,
"done" : function(perm) { if (perm) { self.jqGrid("remapColumns", perm, true); } },
/* msel is either the name of a ui widget class that
extends a multiselect, or a function that supports
creating a multiselect object (with no argument,
or when passed an object), and destroying it (when
passed the string "destroy"). */
"msel" : "multiselect",
/* "msel_opts" : {}, */
/* dlog is either the name of a ui widget class that
behaves in a dialog-like way, or a function, that
supports creating a dialog (when passed dlog_opts)
or destroying a dialog (when passed the string
"destroy")
*/
"dlog" : "dialog",
/* dlog_opts is either an option object to be passed
to "dlog", or (more likely) a function that creates
the options object.
The default produces a suitable options object for
ui.dialog */
"dlog_opts" : function(opts) {
var buttons = {};
buttons[opts.bSubmit] = function() {
opts.apply_perm();
opts.cleanup(false);
};
buttons[opts.bCancel] = function() {
opts.cleanup(true);
};
return $.extend(true, {
"buttons": buttons,
"close": function() {
opts.cleanup(true);
},
"modal" : opts.modal ? opts.modal : false,
"resizable": opts.resizable ? opts.resizable : true,
"width": opts.width+20,
resize: function (e, ui) {
var $container = $(this).find('>div>div.ui-multiselect'),
containerWidth = $container.width(),
containerHeight = $container.height(),
$selectedContainer = $container.find('>div.selected'),
$availableContainer = $container.find('>div.available'),
$selectedActions = $selectedContainer.find('>div.actions'),
$availableActions = $availableContainer.find('>div.actions'),
$selectedList = $selectedContainer.find('>ul.connected-list'),
$availableList = $availableContainer.find('>ul.connected-list'),
dividerLocation = opts.msel_opts.dividerLocation || $.ui.multiselect.defaults.dividerLocation;
$container.width(containerWidth); // to fix width like 398.96px
$availableContainer.width(Math.floor(containerWidth*(1-dividerLocation)));
$selectedContainer.width(containerWidth - $availableContainer.outerWidth() - ($.browser.webkit ? 1: 0));
$availableContainer.height(containerHeight);
$selectedContainer.height(containerHeight);
$selectedList.height(Math.max(containerHeight-$selectedActions.outerHeight()-1,1));
$availableList.height(Math.max(containerHeight-$availableActions.outerHeight()-1,1));
}
}, opts.dialog_opts || {});
},
/* Function to get the permutation array, and pass it to the
"done" function */
"apply_perm" : function() {
$('option',select).each(function(i) {
if (this.selected) {
self.jqGrid("showCol", colModel[this.value].name);
} else {
self.jqGrid("hideCol", colModel[this.value].name);
}
});
var perm = [];
//fixedCols.slice(0);
$('option:selected',select).each(function() { perm.push(parseInt(this.value,10)); });
$.each(perm, function() { delete colMap[colModel[parseInt(this,10)].name]; });
$.each(colMap, function() {
var ti = parseInt(this,10);
perm = insert(perm,ti,ti);
});
if (opts.done) {
opts.done.call(self, perm);
}
},
/* Function to cleanup the dialog, and select. Also calls the
done function with no permutation (to indicate that the
columnChooser was aborted */
"cleanup" : function(calldone) {
call(opts.dlog, selector, 'destroy');
call(opts.msel, select, 'destroy');
selector.remove();
if (calldone && opts.done) {
opts.done.call(self);
}
},
"msel_opts" : {}
}, $.jgrid.col, opts || {});
if($.ui) {
if ($.ui.multiselect ) {
if(opts.msel == "multiselect") {
if(!$.jgrid._multiselect) {
// should be in language file
alert("Multiselect plugin loaded after jqGrid. Please load the plugin before the jqGrid!");
return;
}
opts.msel_opts = $.extend($.ui.multiselect.defaults,opts.msel_opts);
}
}
}
if (opts.caption) {
selector.attr("title", opts.caption);
}
if (opts.classname) {
selector.addClass(opts.classname);
select.addClass(opts.classname);
}
if (opts.width) {
$(">div",selector).css({"width": opts.width,"margin":"0 auto"});
select.css("width", opts.width);
}
if (opts.height) {
$(">div",selector).css("height", opts.height);
select.css("height", opts.height - 10);
}
var colModel = self.jqGrid("getGridParam", "colModel");
var colNames = self.jqGrid("getGridParam", "colNames");
var colMap = {}, fixedCols = [];
select.empty();
$.each(colModel, function(i) {
colMap[this.name] = i;
if (this.hidedlg) {
if (!this.hidden) {
fixedCols.push(i);
}
return;
}
select.append("<option value='"+i+"' "+
(this.hidden?"":"selected='selected'")+">"+colNames[i]+"</option>");
});
function call(fn, obj) {
if (!fn) { return; }
if (typeof fn == 'string') {
if ($.fn[fn]) {
$.fn[fn].apply(obj, $.makeArray(arguments).slice(2));
}
} else if ($.isFunction(fn)) {
fn.apply(obj, $.makeArray(arguments).slice(2));
}
}
var dopts = $.isFunction(opts.dlog_opts) ? opts.dlog_opts.call(self, opts) : opts.dlog_opts;
call(opts.dlog, selector, dopts);
var mopts = $.isFunction(opts.msel_opts) ? opts.msel_opts.call(self, opts) : opts.msel_opts;
call(opts.msel, select, mopts);
// fix height of elements of the multiselect widget
var resizeSel = "#colchooser_"+$.jgrid.jqID(self[0].p.id),
$container = $(resizeSel + '>div>div.ui-multiselect'),
$selectedContainer = $(resizeSel + '>div>div.ui-multiselect>div.selected'),
$availableContainer = $(resizeSel + '>div>div.ui-multiselect>div.available'),
containerHeight,
$selectedActions = $selectedContainer.find('>div.actions'),
$availableActions = $availableContainer.find('>div.actions'),
$selectedList = $selectedContainer.find('>ul.connected-list'),
$availableList = $availableContainer.find('>ul.connected-list');
$container.height($container.parent().height()); // increase the container height
containerHeight = $container.height();
$selectedContainer.height(containerHeight);
$availableContainer.height(containerHeight);
$selectedList.height(Math.max(containerHeight-$selectedActions.outerHeight()-1,1));
$availableList.height(Math.max(containerHeight-$availableActions.outerHeight()-1,1));
// extend the list of components which will be also-resized
selector.data('dialog').uiDialog.resizable("option", "alsoResize",
resizeSel + ',' + resizeSel +'>div' + ',' + resizeSel + '>div>div.ui-multiselect');
}
});
In the case you can continue to use the original minimized version of jquery.jqGrid.min.js and the code which use can be just $(this).jqGrid('columnChooser');. Together with all default settings it will be like
$.extend(true, $.ui.multiselect, {
locale: {
addAll: 'Make all visible',
removeAll: 'Hidde All',
itemsCount: 'Avlialble Columns'
}
});
$.extend(true, $.jgrid.col, {
width: 450,
modal: true,
msel_opts: {dividerLocation: 0.5},
dialog_opts: {
minWidth: 470,
show: 'blind',
hide: 'explode'
}
});
$grid.jqGrid('navButtonAdd', '#pager', {
caption: "",
buttonicon: "ui-icon-calculator",
title: "Choose columns",
onClickButton: function () {
$(this).jqGrid('columnChooser');
}
});
The demo demonstrate the approach. The main advantage of the changes - the really resizable Column Chooser:
UPDATED: Free jqGrid fork of jqGrid, which I develop starting with the end of 2014, contains of cause the modified code of columnChooser.
I get the following error while trying the code on the mobile device.
Result of expression 'selector.data('dialog').uiDialog' [undefined] is not an object.
The error points to the following line of code.
selector.data('dialog').uiDialog.resizable("option", "alsoResize", resizeSel + ',' + resizeSel +'>div' + ',' + resizeSel + '>div>div.ui-multiselect');
When I inspect the code, I find that the data object does not have anything called uiDialog.
just been looking thru the code, try adding this line:
jqModal : true,
to this code:
$grid.jqGrid('navButtonAdd', '#pager', {
caption: "",
buttonicon: "ui-icon-calculator",
title: "Choose columns",
onClickButton: function () {
....
like this:
$grid.jqGrid('navButtonAdd', '#pager', {
caption: "",
buttonicon: "ui-icon-calculator",
title: "Choose columns",
jqModal : true,
onClickButton: function () {
....

Mootools filter plugin

may be you can help me:
Please check this demo: Plugin demo
Plugin description: Plugin description
How can I show only matching items at the top of the list and hide not matching during input typing?
Thanks!
You can do it using onShow and onHide handlers, of course.
See here: http://jsfiddle.net/ypfPY/3/
var myFilter = new ElementFilter('search-term', '#my-list li', {
trigger: 'keyup',
cache: false,
onShow: function(element) {
element.setStyle('display', 'block');
},
onHide: function(element) {
element.setStyle('display', 'none');
}
});
Frankly speaking, I encountered a set of bugs in ElementFilter source (bug on firstly retrieving "showing" and false instead of true for matchOverride when showing all items), so, you better get source from here:
var ElementFilter = new Class({
// implements
Implements: [Options,Events],
// options
options: {
cache: true,
caseSensitive: false,
ignoreKeys: [13, 27, 32, 37, 38, 39, 40],
matchAnywhere: true,
property: 'text',
trigger: 'mouseup',
onStart: $empty,
onShow: $empty,
onHide: $empty,
onComplete: $empty
},
//initialization
initialize: function(observeElement,elements,options) {
//set options
this.setOptions(options);
//set elements and element
this.observeElement = document.id(observeElement);
this.elements = $$(elements);
this.matches = this.elements;
this.misses = [];
//start the listener
this.listen();
},
//adds a listener to the element (if there's a value and if the event code shouldn't be ignored)
listen: function() {
//add the requested event
this.observeElement.addEvent(this.options.trigger,function(e) {
//if there's a value in the box...
if(this.observeElement.value.length) {
//if the key should not be ignored...
if(!this.options.ignoreKeys.contains(e.code)) {
this.fireEvent('start');
this.findMatches(this.options.cache ? this.matches : this.elements);
this.fireEvent('complete');
}
}
else{
//show all of the elements - changed to true
this.findMatches(this.elements,true);
}
}.bind(this));
},
//check for matches within specified elements
findMatches: function(elements,matchOverride) {
//settings
var value = this.observeElement.value;
var regExpPattern = this.options.matchAnywhere ? value : '^' + value;
var regExpAttrs = this.options.caseSensitive ? '' : 'i';
var filter = new RegExp(regExpPattern, regExpAttrs);
var matches = [];
//recurse
elements.each(function(el){
var match = matchOverride == undefined ? filter.test(el.get(this.options.property)) : matchOverride;
//if this element matches, store it...
if(match) {
// default value added
if(!el.retrieve('showing', true)){
this.fireEvent('show',[el]);
}
matches.push(el);
el.store('showing',true);
}
else {
if(el.retrieve('showing', true)) {
this.fireEvent('hide',[el]);
}
el.store('showing', false);
}
return true;
}.bind(this));
return matches;
}
});

Categories