Use JavaScript to add/remove elements from a delimited list

July 7, 2015 at 6:30 pm | Posted in Oracle Developement | 2 Comments

In my APEX application I have a page item that stores a colon delimited list of items, and I want to use JavaScript to add or remove elements from that list.

P1_LIST =”Black:Red:Gold:Blue:White”

Adding An Element

To add an element to the list with JavaScript you could  simple concatenate a color preceded by a colon:
newColor = ‘Green’
$s(‘P1_LIST’, $v(‘P1_LIST’) + ‘:’ + newColor);

This is problematic, if P1_LIST were empty. Then you could end up with:
P1_LIST = “:Green”

To avoid this you can first split the list into an array, “push” the new color to the array, and then write it back as a delimited list:

newColor = 'Green';
arr = $v('P1_LIST').split(':');
arr.push(newColor);
$s('P1_LIST', arr.join(':'));

Removing an Element:

To remove a color from our list is a little trickier. But working with arrays helps. Let’s say we want to remove Blue. We’ll pull the delimited list back into an array (arr). We’ll find the array index of Blue, then loop through arr and push all elements except Blue into a new array (arr2). Lastly we’ll write the new array back to the page item:

arr = $v('P1_LIST').split(':'); //change list into an array
arr.splice(arr.indexOf('Blue'),1); //remove the color blue
$s('P1_LIST', arr.join(':')); //write array back to list

Thanks to Sentinel for the simplified version using splice();

Advertisements

2 Comments »

RSS feed for comments on this post. TrackBack URI

  1. Deleting elements doesn’t need to be tricky, use the splice method of JavaScript Arrays to delete the desired record:

    arr = $v(‘P1_LIST’).split(‘:’);
    arr.splice(arr.indexOf(‘Blue’),1); //delete 1 element starting at idx
    $s(‘P1_LIST’, arr2.join(‘:’)); //write arr2 back to the page item

    • Thanks Sentinel. I didn’t know about splice. So noted in the post.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Entries and comments feeds.

%d bloggers like this: