I have the following JQuery which allows a user to select/de-select a list of items/prices as a way of creating an automatic quotation. The code looks like this:
$('table.products > tbody > tr').click(function(){
if ($(this).find('div.price').is(":visible")) {
$(this).find('div.price, img.selected').fadeOut(100);
} else {
$(this).siblings('div.price, img.selected').fadeIn(100);
}
recalc();
});
It’s actually more complicated than that (hence the reason I haven’t used toggle() but the above is just a simplified example for the purpose of this question.
Anyway, the above code works fine. If the table row is clicked then the price and image are either selected/de-selected depending on what they whether the price was already showing or not.
Then I have a call to a function called recalc(); at the end.. it looks like this (again, this is a simplified version):
function recalc() {
var numOfProducts = $('table.products div.price:visible').length;
alert(numOfProducts);
}
The problem I am having here is that the alert always returns the value that would have been correct before anything was changed.
For example, if there are no div.price visible and I select one, one will become visible but the alert shows 0. Then, if I select another one, that makes 2 visible but the alert only shows 1 because that’s what it was when I clicked. If I then click one of the items I already clicked in order to de-select it, it will display 2
So, my question is how am I supposed to ensure that the function call happens after everything else has been done?
I have come to the conclusion that my approach is completely wrong. I’m basing this partly on the fact that not many people have suggested answers to this question and also partly because the answers I have received don’t accomplish what I’m trying to do. Perhaps my explanation wasn’t clear enough, too.
So, my solution to my original question of getting an accurate report of the number of selected product rows is to create a global variable in JS as so:
Then, add lines to the if statement to increment or decrement the variable depending on what happened:
Now I have an accurate record of the number of selected products in the global variable which I can access at any time to continue the development of my application.