ReynierPM ReynierPM - 23 days ago 9
Javascript Question

How to remove the "," on item deletion?

I have the following piece of code:

<ul class="ul" id="selected_conditions">
<li data-field="asset_locations_name" data-condition="in">
<i class="fa fa-minus-circle delete_condition" aria-hidden="true" title="Click to remove this condition from the list"></i> WHERE asset_locations_name IN(
<span class="condition_item" data-id="1213381233">
<i class="fa fa-minus-circle delete" title="Click to remove this item from the list" aria-hidden="true"></i> 1213381233
</span>,
<span class="condition_item" data-id="1212371897">
<i class="fa fa-minus-circle delete" title="Click to remove this item from the list" aria-hidden="true"></i> 1212371897
</span> )
</li>
</ul>


Each time I click on the little icon
.delete
I should remove the current value and I was able to achieve that with the following code:

$(function() {
$('#selected_conditions').on('click', '.delete', function(ev) {
var item_id = $(this).parent().data('id');
$('.condition_item[data-id="'+ item_id +'"]').remove();
});
});


But the code above has two problems: if I remove any item the symbol
,
isn't removed and that's wrong as an a second one I can't have an emtpy
()
string, so:


  • How do I remove the
    ,
    so I not end up with a bad string like
    (,1213381233)
    or
    (1213381233,)
    ?



Any help? I have leave you a Fiddle to play with. This is a WIP so if you have a suggestion or better solution feel free to add it to your answer.

Answer

Instead of hard-coding the comma(s), I'd use CSS :before to add commas only when there's more than one item in a row.

.condition_item+.condition_item:before {
  content: ", "
}

https://jsfiddle.net/8184ok2e/2/

Comments