Array Power, Part III - DHTML Lab | 4 | WebReference

Array Power, Part III - DHTML Lab | 4

Logo

Array Power, Part III
splice() real world example


There will be many instances in your web applications where you will need to maintain a user-defined list. Naturally, this list will be stored as an array.

How do you allow the user to edit this list in a friendly and intuitive way? The easiest way is with form elements and splice().

For example, in DHTML Dynomat, we have tools for creating the display of our DHTML Fader and Hierarchical Menus. The user enters and edits the headlines or links in a SELECT element, and JavaScript updates an array with the edits quickly and efficiently using splice().

New Book:  

The form on the left is an example of such a list-editing widget.

There is an array called arBooks that stores book titles entered by the user. Highlight a title and click Delete.

Highlight a title, enter a new title in the field provided and click Insert or Replace.

Enter a new title and click Append.

The SELECT list is updated accordingly.

The SELECT list is always updated from the arBooks array. The arBooks array is modified using splice(), whenever you click a button.

The first argument of splice() is determined by the selectedIndex property of the SELECT object, that is, the position of the title you have highlighted. The second argument is always 1, since in this example we are always manipulating a single title. The third argument comes from the New Book field, and is used if you click Insert, Replace or Append.

The complete code for the technique is reproduced in the text area below. You'll notice how clean and compact the JavaScript is when one uses splice().


Finally, let's take all the prototyped methods we have created in this series of articles and create a use-everywhere external JavaScript file.


Produced by Peter Belesis and

All Rights Reserved. Legal Notices.
Created: May 16, 2000
Revised: May 16, 2000

URL: https://www.webreference.com/dhtml/column33/12.html