Syed
Syed

Reputation: 2597

Adding class based on td value using jquery

I have rows in the following way.

<table id="tblInbox">
<tbody>    
    <tr class='active'><td>Daily Price</td><td>1</td><td>Santosh</td></tr>
    <tr class='active'><td>Daily Price</td><td>2</td><td>Star</td></tr>
    <tr><td>Weekly Price</td><td>3</td><td>Zakeer</td></tr>
    <tr><td>Weekly Price</td><td>4</td><td>Ubed</td></tr>
    <tr><td>Weekly Price</td><td>5</td><td>xyz/td></tr>
    <tr><td>Daily Price</td><td>6</td><td>India</td></tr>
    <tr><td>Daily Price</td><td>7</td><td>Australia</td></tr>
</tbody>
</table>

I will display rows which are having class 'active' by using

function displayActiveRows(){ // Displaying active rows
    $("#tblInbox tbody tr").each( function(){ 
    if($(this).hasClass('active')) { // If the row has class.
        console.log("has class");
        $(this).show(); // Display the row.
    } else {                
        $(this).hide(); // Hide the row.
    }       
    });
}

On pressing "Next" button, I'd like to add class to only next 2 0r 10 (whatever the count is) rows which are having first td value as "Daily price" by removing the class to existing rows. My code is like this.

$(document).on('click','#nextPage',function(){ // Clicking Next Button.
    // Remove class to already existing class rows.
    $('.active').removeClass('active');     
    // Confused here. 
 });

Can you suggest me, guys?

Upvotes: 2

Views: 3126

Answers (2)

Adil
Adil

Reputation: 148110

You can use :first-child and :contains

Live Demo

$(document).on('click','#nextPage',function(){ // Clicking Next Button.  
    $('.active :first-child:contains("Daily Price")').removeClass('active').addClass('inactive'); 
});

To check irrespective of tr class you can use tr in selector instead of .active

Live Demo

$(document).on('click','#nextPage',function(){ // Clicking Next Button.  
    $('tr :first-child:contains("Daily Price")').removeClass('active').addClass('inactive'); 
});

To toggle class beteen rows you need to iterate using each.

Live Demo

$(document).on('click','#nextPage',function(){ // Clicking Next Button.  
    $('tr :first-child:contains("Daily Price")').each(function(){       
       if($(this).parent()[0].className === '')
           $(this).parent().addClass('active');
        else
        if($(this).parent()[0].className == 'active')        
           $(this).parent().removeClass('active');  

    });
});

You can use conditional opertator also

Live Demo

$(document).on('click','#nextPage',function(){ // Clicking Next Button.  
    $('tr :first-child:contains("Daily Price")').each(function(){       
        $(this).parent()[0].className = $(this).parent()[0].className === "active" ? "" : "active";
    });
});

Upvotes: 3

Magesh
Magesh

Reputation: 484

try this

$("#tblInbox tbody tr").children("td:contains('Daily Price')").parent().addClass('active')

Upvotes: 0

Related Questions