Reputation: 431
I am mostly there but cant seem to crack this, I have a simple form with check boxes,
form#bookingsToDelete(
action='/list/batchDelete'
method='POST'
autocomplete='off'
)
tbody
each doc in list
-var id = doc._id;
tr
td
input.form-control(type='checkbox' name='ids[]' id='doc._id' value=doc._id onclick='return selectedForDelete();' )
td.bg-blue= doc.tourDate
td
and a counter which should update depending on how many boxes have been selected. Using below JQuery I am able to increment up but when I click a selected checkbox (to deselect the item) it wont increment down by one and I don't understand why.
div.p-2.actionMenu-2.float-right
button.btn.btn-danger(type='submit' form='bookingsToDelete' value='Submit')
span Delete
span.deleteCounter.badge.badge-light
custom.js
let bcount ='1';
function selectedForDelete() {
if ($('input:checkbox').is(':checked') ) {
$('input:checkbox:checked').addClass('checked');
$('.deleteCounter').text( bcount ++ );
} else {
$('input:checkbox').removeClass('checked');
$('.deleteCounter').text( bcount -- );
}
}
I have tried bcount +1
bcount -1
and moving the var declaration inside the function. If I click only one checkbox the counter increments up and down but as soon as I select multiple check boxes the counter goes up but doesn't go down when I deselect the box.
Please, any guidance would b much appreciated!
Upvotes: 2
Views: 1679
Reputation: 337590
The issue is because your jQuery selector in the if
condition, $('input:checkbox')
is selecting all the checkboxes in the page. When you then call is()
on that it only interrogates the checked state of the first one.
To fix this you need to get a reference to the element which raised the change event. The best way to do that is to attach your event handlers unobtrusively. Try this:
jQuery(function($) {
var bcount = 1;
$('input:checkbox').on('change', function() {
var $el = $(this);
if ($el.prop('checked')) {
$el.addClass('checked');
$('.deleteCounter').text(++bcount);
} else {
$el.removeClass('checked');
$('.deleteCounter').text(--bcount);
}
});
});
However this is still not optimal. It's not DRY and it contains a global variable (global within the scope of jQuery's document.ready handler anyway). A better approach would be to simply count the number of checked boxes under each event. You can also avoid the addition/removal of the class by simply using the :checked
selector in CSS
jQuery(function($) {
$('input:checkbox').on('change', function() {
$('.deleteCounter').text($('input:checkbox:checked').length);
});
});
input:checked {
/* your styling here... */
}
Upvotes: 3