ReynierPM ReynierPM - 26 days ago 7
Javascript Question

How to count the elements on deletion so I not end up with an empty ()?

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 a problems: if I remove all the items I will end up with the following
()
empty string and I can't have it so:


  • How do I count the SPAN inside the parenthesis
    ()
    and trow an alert if I am clicking on the last one?




Note: The right behavior would be show a confirm dialog to the user
and if the user click on OK and agree to remove the last item then the
whole condition should be removed. Meaning if I click on the last element the > whole parent
li
should be removed.


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

I've upgrading your jsfiddle example, please check it

$(function() {
    $('#selected_conditions').on('click', '.delete', function(ev) {
        var item = $(this).closest(".condition_item");
        var condition = $(this).closest(".condition");
        var items = condition.find(".condition_item");
        if(items.size() > 1) {
            item.remove();
        } else {
            if(confirm("Removing last item will remove whole condition. Continue?")) {
                condition.remove();
            }
        }
    });
});

https://jsfiddle.net/br3t/8184ok2e/8/