Use JavaScript to add/remove elements from a delimited list

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.


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:

[sourcecode language=”javascript”]newColor = ‘Green’;
arr = $v(‘P1_LIST’).split(‘:’);
$s(‘P1_LIST’, arr.join(‘:’));[/sourcecode]

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:

[sourcecode language=”javascript”]
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[/sourcecode]

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

2 thoughts on “Use JavaScript to add/remove elements from a delimited list

  • July 10, 2015 at 5:23 pm

    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

Comments are closed.