cooking, programming and everyday life xrado

Thursday, February 19, 2009

Dynamic select boxes

These days i was working on a project, where i needed dynamically loading select boxes. I first tried mootools native methods like removing and injecting new option elements in to select element. That worked just fine in FF, but as you expect in IE did not. IE's select box stood unchanged. I remember while ago i have to re-inject the whole select box to see the changes in IE.

According to DOM, there is a better way. HTMLSelectElement support add and remove method that work in all major browsers. So i have implemented three basic methods for mootools Element class.
Element.implement({
	removeAllOptions: function() {
		if(this.get('tag')!='select') return this;
		for(var i=this.options.length-1;i>=0;i--) this.remove(i);
		return this;
	},

	addOption: function(text,value) {
		if(this.get('tag')!='select') return this;
		var optn = new Element('option');
		if(text) optn.text = text;
		if(value) optn.value = value;
		this.options.add(optn);
		return this;
	},

	removeOption: function(prop,value){
		if(this.get('tag')!='select') return this;
		for(var i=this.options.length-1;i>=0;i--) {
			if (prop=='selected' && this.options[i].selected) this.remove(i);
			if (prop=='value' && this.options[i].value==value) this.remove(i);
			if (prop=='text' && this.options[i].text==value) this.remove(i);
			if (prop=='index' && i==value) this.remove(i);
		}
		return this;
	}
});
Methods hopefully already explaining their self.

USAGE
// remove all options or empty select box
$('selectbox').removaAllOptions();

// add options, one after another
$('selectbox').addOption('One',1).addOption('Two',2).addOption('Two',3);

// removing options 
$('selectbox').removeOption('text','One');
$('selectbox').removeOption('value',2);
$('selectbox').removeOption('selected');
$('selectbox').removeOption('index',0);
happy selecting ;)
A ne bi moralo v USAGE biti napisano addOption in removeOptioon? V implementaciji je namreč zapisano v ednini, v usage pa je uporabljena množina... addOptions in removeOptions...

Lep pozdrav s tvojega bivšega Asus Eee PC.

damn, imas prav ..niso stestirani snipeti ..hvala za info

pozdrav tebi in tvojmu tamalmu eeeji

09:28, Tuesday, April 12, 2011 serggn, from russia
// remove all options or empty select box
$('selectbox').removaAllOptions();

there is a mistake in code: removaAllOptions();

wadawdwadwa

COMMENTS ARE DISABLED