zero vacpls zero vacpls - 4 months ago 17
jQuery Question

jQuery on click toggle event

I've made a function which selects an item when you click on it. And made it so when I've selected more than 10, it stops adding to

selectedItems
.

But when 10 items is selected, I can still toggle the class
d-items-selected
by clicking. How do I disable that? I've tried to use
stop()
but that canceled the hole thing, so I couldn't 'de-select' the items again.

$(document).ready(function(){
$('.d-items').on('click', function(e){
e.preventDefault();
$(this).toggleClass('d-items-selected');
var selectedItems = $('.d-items-selected').length;
if(selectedItems > 10) {
$('.d-items').finish();
} else {
$('#ItemsSelected').html(selectedItems);
}
});
});

Answer

You can disable controls which are not selected. Something like this.

$(document).ready(function(){
        $('.d-items').on('click', function(e){
            e.preventDefault();
            $(this).toggleClass('d-items-selected');
            var selectedItems = $('.d-items-selected').length;
            if(selectedItems > 10) {
                //do not allow to select
                $(this).removeClass('d-items-selected');
            } else {
                $('#ItemsSelected').html(selectedItems);
            }
        });
    });
Comments