Reputation: 3228
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
Upvotes: 1
Views: 1113
Reputation: 493
have you tried toggleClass()
instead of removing and adding classes ?
Upvotes: 1
Reputation: 2343
Based on what you're describing perhaps the toggleClass function would work better for you.
From the API documentation:
.toggleClass( function(index, class, switch) [, switch] ) function(index, class, switch)A function that returns class names to be toggled in the class attribute of each element in the matched set. Receives the index position of the element in the set, the old class value, and the switch as arguments. switchA boolean value to determine whether the class should be added or removed.
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.
Upvotes: 2