I would like to remove the default functionality of clicking anywhere on a list item for it to be removed. Instead, I’d like to add a custom remove button that deletes the list item. Here’s what I’ve got so far.
<pre>
var sl = $('select#api_product').selectList({
instance: true,
clickRemove: false,
onAdd: function (select, value, text) {
$('.selectlist-item').last().after('<span class="delete"></span>');
}
});
$('<span class="delete"></span>').insertAfter('.selectlist-item').last();
</pre>
Using this code, I’m able to remove the click target on the list item and add span tag which has a delete icon as a bg image. However, I don’t know how to remove the list-item and select option after clicking the span tag.
I haven’t used selectList before, but a quick glance and some quick jsfiddle work (I borrowed one of the selectList examples) at it makes it look like adding a delegated event handler to the selectList classed
ulshould be able to take care of it.One caveat: the easiest way to do this for selection is to put the .delete span inside the appropriate
li. Personally I think it’s also the closest to being semantically correct, since that delete “belongs” to that particularli. There are a couple of different ways to handle an approach where the deletes are outside of theliand that shouldn’t be terribly hard to figure out, but this was faster to reach a working demonstration for me:Basically selectList has a specific
remove(value)function which then removes both the element and de-selects it within the list, you just have to go back to your selectList element and call that remove function using the value of the item being removed, which selectList stores via data() as value.I also removed your
insertAfteras it seems completely unnecessary. Note the change to ‘append’ in theonAddfunction. If your .delete span has to be in a following rather than contained element, you will either need to use sibling selectors or attach the data to the span as well when it is created, or use some similar method.Note: if you’re creating your selectlists on the fly you will need to attach the
.onto something containing them, and probably change the selector to'.selectlist-item .delete'to keep it specific.