I have a button that when clicked, should only execute its code if the number of div that have the class of “like” is greater than 0. The problem is that even if this is true, the button still won’t execute its code. Note that I have tried both .length and .size() to the same result.
$(document).ready(function() {
countlikes = $('[id^=post_].like').length;
likestatus = 1;
$('#show_likes').on('click', function() {
if (countlikes >0) {
likestatus++;
$('[id^=post_].like').toggle();
if (likestatus % 2 == 0) {
$('#hidelikedbtn').removeClass('hidelikedimgoff').addClass('hidelikedimgon');
} else {
$('#hidelikedbtn').removeClass('hidelikedimgon').addClass('hidelikedimgoff');
}
return false;
} else {
return false;
}
});
});
Any ideas?
Assuming that the number of elements with “like” class varies after the page loads, the problem is that you currently assign a value to
countlikesonly once, outside your click handler, so every time the handler runs it will be using the originalcountlikesvalue and not a current count. Move the assignment inside the handler and it should work. (Though given the variable is only actually used in one place at the moment you don’t really need it, you can just test$('[id^=post_].like').lengthdirectly in your if statement.)Also your question says “greater than 1” and your code says “> 0”, so even if it worked it wouldn’t be doing what you describe.
Also, unrelated to your problem, the last
elsecase is redundant: at the end of theifyou return false, and in the else you return false, so why not just move thereturn false;outside the if and delete the else?