I have a script that increments a counter when an item is added to a dropdown list. This is working fine. However, I need a way to decrement the counter if the item is removed from the list.
I am struggling to find a way to do this with the code I have and would appreciate it if someone could help me code this. I am using jQuery chosen plugin to populate the list from a button click. I have posted the js but if you need the HTML i shall be happy to post. Just posting the js code to keep post to a minimum. Many thanks.
js
$(function() {
$(document).on('click', '#add', function() {
var boxvalue = $("#box_input").val();
if (boxvalue ==''){
$("#niinputmessage").fadeIn(3000).html('No blank entries').fadeOut(5000).css({ 'color': 'red', 'margin-left': '5px', 'margin-top': '5px' });
return false;
}
var count = $("#box_ni :selected").length;
$("#counter").html("Total selected boxes for intake: " +
'<span style="font-size: 14px; color: white;">' +
'( ' + count + ' )' +
'</span>').css('color:, black');
if (count > 2) {
$("#counter").html("No more than 3 items per intake");
return false;
} else {
count++;
$("#counter").html("Total selected boxes for intake: " +
'<span style="font-size: 14px; color: white;">' + '( ' + count + ' )' +
'</span>').css('color:, black');
}
$("#box_ni").attr("data-placeholder", "Select boxes for intake... ");
$("#box_ni").append("<option selected>" + boxvalue + "</option>");
$("#box_ni").trigger("chosen:updated");
$("#box_input").val('');
});
});
html
<div class="form-group">
<label for="box_input" class="labelStyle">Enter Your Box(es)</label><br />
<input type="text" id="box_input" name="box_input" disabled />
<input type="button" id="add" Value="Add" disabled />
<div id="niinputmessage"></div>
<div class="servicesHelp"><lead id="serviceHelp" class="form-text text-muted">Please select your boxes from the list. You can select a max of 3 boxes per submission. You can select multiple boxes by holding the left ctrl on your keyboard and making your selection</lead>
</div>
<div class="noBrtvBoxes" style="color:white;"></div>
</div>
<div id="counter" style="margin-left: 7px; font-size: 14px; color: #c5ba7a;">Total selected boxes for intake: 0</div><br />
<div class="message">
<div class="sucMsg">
</div>
</div>