Click here to Skip to main content
15,884,237 members
Articles / Programming Languages / Javascript

JavaScript Advanced List

Rate me:
Please Sign up or sign in to vote.
4.53/5 (9 votes)
3 Aug 2009CPOL7 min read 104.6K   1.1K   28   8
An advanced list that works with all objects

Introduction

When you work with a list of objects in Ajax, it is very important to add, delete, find objects in the list but JavaScript array does not contain any of them. We need to create an advanced list that works with all objects. In .NET platform, there is "Generic List" class that can do the same. My function is like that one. We can say its name: an Array with dynamic size. (In JavaScript, it is impossible to remove items from an array or resize an array.)

Another use of this tool is for creating two lists that can change and move position of items in the list. I create a SelectList function that can load select or dropdown items and load all items to a list object. It is possible to resize dropdown, move items and also remove items from it.

Using the Code

Creating a list of items is simple and you can hold any objects in it. You can also define and override isEqual function for finding items in a list:

JavaScript
var mylist = new generic.list();

The question arises: What I can do with this list? Your answer is:

  • Add to List
  • Insert to specific position in List
  • Remove from List
  • Remove from specific position in List
  • Find in List
  • Clear List
  • Join List
  • Add Range of Array Items to List

For example, we get a list of checked checkbox in a form for sending to the server using Ajax:

JavaScript
var chklist = new generic.list();

// function that attach to input checkbox click event
function check(el){
	if(el.checked){
		chklist.add(el.value);
	}else{
		chklist.remove(el.value);
	}
}

You just add simple code to get the list, it is possible to prevent the user from adding equal objects to list:

JavaScript
// function that attach to input checkbox click event [Prevent Duplicate]
function check(el){
	if(el.checked){
		if(!chklist.find(el.value))
			chklist.add(el.value);
	}else{
		chklist.remove(el.value);
	}
}

Find function returns an integer value if it is greater than -1, an object is found and value is first seen of item's position. It uses the compare function. compare function in normal condition just returns that if two objects are equal and use "=" operator, but if we use complex objects, how do we compare them?

You can override the isEqual function for complex objects:

JavaScript
var mylist = new generic.list();
mylist.isEqual = function(a, b){
	return (a["id"] == b["id"] && a["name"] == b["name"]);
}
mylist.add({id:1,name:"Mahdi"});
mylist.add({id:2,name:"Alireza"});
mylist.add({id:3,name:"Rouzbeh"});
var result = mylist.find({id:1,name:"Mahdi"});
// result is 0 (position of result)

The following table shows the full methods and properties of the generic.list object:

Method NameResult
item(index,object)Get and set item in index position, if need to get item just use index parameter, for setting use index and input object. 
itemsIt is property of list (not a function). It will hold data array. You can use this for working with your array and use all methods of normal array on it.
property(index, property, value)Get and set property for an item. If you need to get just use two first parameter, else need all three parameter for setting.
extend(index,obj)This is another way to set property for an object in list. The second parameter must be an object.
add(item)Add one item to list
insert(item,index)Insert item at specified [index]
addRange(arrayObj)Add list of items at end of list
find(item)Find first position of item, if not found return -1
isEqual(a,b)Compare two objects in list and return true or false, if true, a and b are equal
remove(item)Remove item from list
removeAt(index)Remove item at [index] position
join(seprator,property)Join list of items, if list contains complex object you need to specify property
clear()Clear and empty list

Now you can see some functionality of generic.list, but one of the tools that is very important if another object uses this class is selectlist.

What can do this function? Let's see a sample:

We have two select lists with multi-select attribute set to true, we need to move items from BOX 1 to BOX 2. We also need to change Priority of items in BOX-2 (Target):

Preview of Select List

With selectlist function, it is very simple and easy. Just see the code:

JavaScript
var second, first;
function load(){
second = new  selectlist("secondbox");
second.load();
first = new selectlist("firstbox");
}

This function must be loaded after HTML codes of box or in page-load. For adding selected Items from BOX-1 to BOX-2, we need addFrom method from the second box:

JavaScript
second.addFrom('firstbox',true)

The first parameter is ID of BOX-1 and second parameter is an option to remove the moved items to the second box or just copy them.

Also it is possible to move items in the box. Let's move the priority of selected items in BOX-2:

JavaScript
second.move(true)

When using the move method, the parameter says that move direction is UP or not. False means DOWN. You can do it with one line of code!

selectlist is very powerful, we can see other functionality of it. For example, for complex objects, we can load Data from server dynamically to a dropdown or select list. Each selectlist object and normal DOM select list has options property. But options in selectlist is a generic.list object.

Example of complex objects:

JavaScript
var SampleServerData = [{id:1,code:"First Item"},{id:2,code:"Second Item"}];
var boxlist = new selectlist('boxid');

//Clear box data
boxlist.clear(true);

//Add server json data to list
boxlist.options.addRange(SampleServerData);

//set value and text (Which property is Text and Which is Value of box
boxlist.setValue("id");
boxlist.setDisplay("name");

boxlist.build();

First I clear data from the box. Next all results to Box but select list need to know which property of items is TEXT and which is VALUE of items in box, then call build that shows the result.

There are some other methods that help you to work with object. The following table shows a list of full methods of this object (dd: means drop-down):

Method NameResult
new: selectlist(ID,autoload)When you create a new item, you need ID of drop-down list, and optional 'autoload' Boolean parameter that indicates load items from drop-down to object.
getOptions()Get options of 'DD' as generic.list object
setOptions(glist)Set options of 'DD' as generic.list object
find(text,value)Find item with this text and value, return index of item, if not return -1
findItem(item)Find specific item in list
newObject(text,value)Create new object with specified text and value: "HELPER"
add(text,value,rebuild)Add item to end of list with specified text and value, if you need to re-create list, set rebuild option to true
addItem(item,rebuild)Add an item at end of list, if you need to re-create list use optional Boolean rebuild parameter
insert(txt,val,index,rebuild)Insert item with specified text and value at [index] position. Use rebuild to re-create 'dd'
insertItem(item, index, rebuild)Insert item at specified [index]
addRange(itemsArray, rebuild)Add an array list of items to list
remove(text, value)Remove item with this text and value
removeItem(item)Remove item from list
removeAt(index)Remove item at [index] position
join(separator, property)Join list of items in list return string. If property does not specify use 'value' as default property
setValue(string)Set name of property of object to use for value in list
setDisplay(string)Set name of property of object to use as text in list
getName(index)Get text of item in [index] position
getValue(index)Get value of item in [index] position
getPorperty(index,property)Get property of item in [index] position
getJson(dataset)Return string format in json type of list. Optional dataset name to use for json data
clear(old)Clear 'DD' items, if old value set to true, remove all list items in options in object. In other words, set old value to clear object entire.
build()Rebuild items of 'DD' based on items in this object
load()Load items from 'DD' to object list
selectedIndex()Return a generic.list object that contains all selected index in 'DD' list.
removeSelected()Remove all selected items in 'DD'
setSelectedIndex(Index)Set item at [index] position in 'DD' selected
setSelectedValue(value)Find item with this value and set it as selected
setSelectedIndexs(indexList)Set all index in array selected
setSelectedValues(values)Set all items with these values selected
addFrom(sourceID, remove)Add items from another 'DD', Optional parameter to remove items that inserted from source 'DD'
move(upMode)Move index (Position) of selected items in 'DD', Up Mode parameter set direction of move. Each run of function decrease/increase index one.

Points of Interest

I think many other functionalities can be done by these codes, like other objects or you can use it to hold table rows and change them in memory. You can download the sample code and enjoy!

I build useful JavaScript dataset and data repeaters and in my next article I will describe them. They are based on this generic.list object.

Update Note

In the comments, Jeffrey Scott Flesher guided me to get some better functions in Add, Remove and Insert. I use his code for better performance. Thanks everyone for commenting.

History

  • 2009/08/02
  • 2008/10/27
    • One little bug in selectlist
    • Added more methods, fixed bug in complex object join
  • 2008/9/29
    • Bug in json format fixed

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer Raahbar co.
Iran (Islamic Republic of) Iran (Islamic Republic of)
I am web developer and .net programmer focusing on Asp.net MVC and Webforms development.

Comments and Discussions

 
GeneralI like it very much Pin
shevc17-Sep-09 0:08
shevc17-Sep-09 0:08 
Laugh | :laugh: I like it very much! It works very well!!
Generalreport style list Pin
Chen Jiadong30-Dec-08 19:45
Chen Jiadong30-Dec-08 19:45 
GeneralShowing text data from a file into the cells of the grid Pin
AlexEvans4-Nov-08 11:47
AlexEvans4-Nov-08 11:47 
AnswerRe: Showing text data from a file into the cells of the grid Pin
Mahdi Yousefi4-Nov-08 17:45
Mahdi Yousefi4-Nov-08 17:45 
GeneralOptimize Pin
Jeffrey Scott Flesher26-Oct-08 19:44
Jeffrey Scott Flesher26-Oct-08 19:44 
GeneralRe: Optimize Pin
Mahdi Yousefi26-Oct-08 21:28
Mahdi Yousefi26-Oct-08 21:28 
GeneralRe: Optimize Pin
Jeffrey Scott Flesher27-Oct-08 7:33
Jeffrey Scott Flesher27-Oct-08 7:33 
GeneralRe: Optimize Pin
Mahdi Yousefi27-Oct-08 19:57
Mahdi Yousefi27-Oct-08 19:57 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.