0

I have been working on a custom select where every added service will increase the cost on first input. Then within the same category it wouldn't add any more.

https://jsfiddle.net/0mvubg2L/1/

On first click of the Class 45 category service, it should add 100, then after that it should calculate 0. But it's adding all the elements together to make 300.

Then if you were to add a service from Class 44, it would also add 100, and so on.

I tried making an update function

function update(param) {
    var total = 0;

    $(".search-results .results-group.ready .item, .search-results .results-group.added .item").each(function() {
        total += + param;
    });

    $(".total").text(total); 
}

and then making an on click to send it through, but I can't figure out the correct method to implement this.

var itemReady = $(".search-results .results-group.ready .item");

itemReady.on("click", function() {
    $(this).parent().removeClass('ready');
    $(this).parent().addClass('added');

    update('100');
});

itemAdded.on("click", function() {
    update('0');
});

1 Answer 1

2

In your fiddle there are a few issues:

  1. you were suming up all the items, not just the .active ones
  2. you could just pass a number instead of a string and then you don't need the '+' in total += + param, looks weird.
$(function () {

    function update(param) {
        var total = 0;

        if ($(".search-results .results-group.ready .item.active").length > 0) {
            total = param;
        }

        $(".total").text(total);
    }

    $(".search-results .results-group.ready .item").on("click", function(){
        $(this).hasClass('active') ? $(this).removeClass('active') : $(this).addClass('active');
        update(100);
    });

});
Sign up to request clarification or add additional context in comments.

1 Comment

That calculation works great, but I face quite the unusual scenario where after the first service is added, and adds the 100, the follow server 2 and 3 then should add 0. But the second category group should also add 100 on the first click, then after that only 0. So the totals all added up would then be 200. Sorry it's such a weird request, you've certainly helped me on my way though.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.