I have a certain number of divs that each have a data-value associated with them. When a user selects the div a class is added to the div. I would like to update the value of an input box depending on which div has a class added. I would also like to decrease the value if the user clicks on the box a second time to remove the class. Here is my jQuery:
$(".vendor-icon").click(function() {
$(this).toggleClass('vendor-icon-active');
var total = 0;
var item = $(this);
if ($(item).hasClass('vendor-icon-active')) {
total = total + $(item).data('value');
}
if (!$(item).hasClass('vendor-icon-active')) {
total = total - $(item).data('value');
}
});
Here is an example of how the divs are set up:
<div class="vendor-icon website-management" data-value="300"></div>
<div class="vendor-icon make-an-offer" data-value="200"></div>
<div class="vendor-icon email-marketing" data-value="100"></div>
If the first and second div are selected, then the value of the input should be 500. If the second of third div is selected, then the value of the input should be 300.
Right now, if the user selects the first div, the value is 300. If they then select the second div, the value changes to 200 and not 500. Also, if the user clicks on the first div the value will show 300 but if they click the div again, the value will change to -300 instead of 0.