I'm trying to bind a two-stage click behavior to paragraph elements returned from an ajax call. This is NOT a question about using on(), I get that. I'm trying to figure out why the second part of my statement isn't working.
HTML is:
<div class="lesson odd">
<p class="lesson-text 25 lesson-selected">
<input type="hidden" name="lesson-id" value="25360">
<input type="hidden" class="lesson-day-number" value="25">
<span class="lesson-name">25 Lovely Lesson Name</span>
<span class="lesson-price">¥18,000</span>
<br>
<span class="lesson-short-name"></span>
<span class="lesson-time">1:30pm - 3:30pm</span>
<a class="lesson-details" href="#" data-hasqtip="2" oldtitle="Lovely description details" title="">
<i class="fa fa-question-circle fa-lg lesson-desc-popup"></i>
</a>
</p>
</div>
JQuery is:
// bind click function
// click on lesson to select, click again to de-select
jQuery('p.lesson-text').on("click", function() {
if (jQuery(this).not('.lesson-selected')) {
// reset all selections for this day
var dayValue = jQuery(this).children().next('.lesson-day-number').val();
jQuery('p.lesson-text.lesson-selected.' + dayValue).removeClass('lesson-selected');
// add selected class
jQuery(this).removeClass('deselected');
jQuery(this).addClass('lesson-selected');
// set all other lessons for that day to deselected
jQuery('p.lesson-text.' + dayValue).not('.lesson-selected').addClass('deselected');
} else if (jQuery(this).is('.lesson-selected')) {
// reset all selections for this day, remove all deselected
var dayValue = jQuery(this).children().next('.lesson-day-number').val();
jQuery('p.lesson-text.lesson-selected.' + dayValue).removeClass('lesson-selected');
jQuery('p.lesson-text.deselected.' + dayValue).removeClass('deselected');
}
}); // end click function
So the click behavior works fine for the first click. The user clicks on the lesson desired, and the "lesson-selected" class is added. If the user clicks on a different lesson, also no problem. The "lesson-selected" class is added, and all other lessons for that day are marked "deselected". So it seems the top part of the JQuery is working fine.
However, when I click on a p.lesson-text that already has the "lesson-selected" class, nothing happens. It should be clearing the class on that p.lesson-text, and clearing all the other "deselected" p.lesson-text elements as well. What am I doing wrong here? Please help!