Here is my jquery:
// Show all instances
var link = $('<a class="show-instances" href="#">Show all instances</a>');
$('tr.main').hide().first().find('.product').parent().remove('a').append(link);
$('tr.main').first().show();
$(function () {
$(".show-instances").click(function (e) {
e.preventDefault();
$(".show-instances").addClass('selected').not(this).removeClass('selected');
var selectedClass = $(this).closest('tr.main').attr('class').split(' ');
$('.' + selectedClass[1]).not(':has("a.show-instances")').toggle();
return false;
})
});
Adding the anchor works and on click adding the class works – I just don’t understand why on click the class added “selected” won’t remove when a user clicks the anchor the 2nd time?
So when a user clicks the anchor “show-instances” class “selected” will add to the anchor – I need the class to be removed when it’s clicked again.
Am I missing another function?
Any suggestions?
/******RESOLVED*******/
Using the Toggle class – here is the jquery:
// Show all instances
var link = $('<a class="show-instances" href="#">Show all instances</a>');
$('tr.main').hide().first().find('.product').parent().remove('a').append(link);
$('tr.main').first().show();
$(function () {
$(".show-instances").click(function (e) {
e.preventDefault();
$(this).toggleClass("selected");
var selectedClass = $(this).closest('tr.main').attr('class').split(' ');
$('.' + selectedClass[1]).not(':has("a.show-instances")').toggle();
return false;
})
});
Also here is a Jsfiddle link to see
Based on what you’re describing perhaps the toggleClass function would work better for you.
From the API documentation:
Although this one seems pretty straightforward, it can also help if you post these type of questions up on jsfiddle so people can see what you’re trying to achieve.