June 20, 2006

Using MochiKit to Move Items Between Select Lists

If you are writing client side JavaScript you should be using MochiKit. I found myself needing to implement two select list boxes where items are moved from one to the other. I was able to implement this with some very concise JavaScript thanks to MochiKit's functional programming and DOM manipulation APIs.
    function makeOption(option) {
return OPTION({"value": option.value}, option.text);
}

function moveOption( fromSelect, toSelect)
{
// add 'selected' nodes toSelect
appendChildNodes(toSelect,
map( makeOption,
ifilter(itemgetter('selected'), $(fromSelect).options))
);

// remove the 'selected' fromSelect
replaceChildNodes(fromSelect,
list(ifilterfalse(itemgetter('selected'), $(fromSelect).options))
);
}

You can see a working example.

There are longer and more complete examples out there, but you should be able to implement all of the functionality that they provide using MochiKit.

savoy savoy