Ramirez
Ramirez

Reputation: 193

Set active class on one element at the time

What I have is a table representation of available times/date. The user is able to choose a time by clicking on the link "Choose". When clicking on this link the class "active" is set, but what I want is when the user chooses a other time the previous class is removed and set on the new element only.

What I have so far:

<div class="wrapper-div">
    <div class="row">
        <div class="date">monday, 2015 09 02 </div>
        <div class="time">12:10</div>
        <div class="select"><a href="#">Choose <span class="select-arrow"></span></a>            
   </div>
    </div>
    <div class="row">
        <div class="date">thuesday, 2015 06 22</div>
        <div class="time">12:30</div>
        <div class="select"><a href="#">Choose <span class="select-arrow"></span></a></div>
    </div>
    <div class="row">
        <div class="date">wensday, 2015 02 9</div>
        <div class="time">09:15</div>
        <div class="select"><a href="#">Choose <span class="select-arrow"></span></a></div>
    </div> 
</div>

jQuery code:

$('.select a').click(function(e){
    e.preventDefault();
    $(this).parents().eq(1).addClass('active');
    $('.wrapper-div div').each(function(){
        removeClass('active');
    });
});

And my working fiddle: http://goo.gl/E5hhyn

What is the best way to solve this?

Upvotes: 0

Views: 2273

Answers (4)

Jodo
Jodo

Reputation: 4773

you first add the Class and than you remove all of the "active" classes, if you first remove all the classes "active" and then add it to the clicked one it should work.

$('.wrapper-div .row').each(function(){
    $(this).removeClass('active');
});
$(this).parents().find(".row:first").addClass('active');

Upvotes: 0

James
James

Reputation: 67

You could use jQuery's .find() method to find the class you want to remove, then use jQuery's .remove() method to remove the class. With the class now gone, just add your new .active class.

Upvotes: 0

Naeem Shaikh
Naeem Shaikh

Reputation: 15725

working fiddle http://jsfiddle.net/gtog33qk/1/

$('.select a').click(function(e){
    e.preventDefault();
    $('.wrapper-div div').each(function(i,e){
        $(e).removeClass('active');
    });
    $(this).closest('.row').addClass('active');

});

Just changed a little code, used closest to find the complete active row, and you need to use removeClass on an element, as explained by Rory

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337714

Your each syntax is incorrect as you don't call removeClass on any jQuery object. The need for each itself is redundant anyway. Try this:

$('.select a').click(function(e){
    e.preventDefault();
    $('.wrapper-div div').removeClass('active'); // remove first
    $(this).parents().eq(1).addClass('active');
});

Upvotes: 4

Related Questions