Tushar Gaurav
Tushar Gaurav

Reputation: 506

how to reset class of table's rows after prepending a row

I am prepending a row every time user adds a new row without refreshing the page. and for resetting the class of rows I am using .each() but its not working properly. Its adding odd class to every new row.

$("#tbadver").prepend("<tr id='tr_"+advID+"'>"
    +"<td >"+advName.val()+"</td>"
    +"<td >"+email.val()+"</td>"
    +"<td >"+phone.val()+"</td>"
    +"<td >"+mobile.val()+"</td>"
    +"<td >"+contactName.val()+"</td>"
    +"<td >"+contactEmail.val()+"</td>"
    +"<td >"+contactMobile.val()+"</td>"
    +"</tr>");
jQuery(".tbl-grid tr").each(function(e)
{
    $(e).find("tr:odd").addClass("odd");
    $(e).find("tr:even").addClass("even");
});

Upvotes: 0

Views: 163

Answers (3)

soyuka
soyuka

Reputation: 9105

You should first reset all table classes :

$("tbl-grid tr").removeClass("odd even");
$("tbl-grid tr:odd").addClass("odd");
$("tbl-grid tr:even").addClass("even");

You don't need to parse all tr with each, just parse the dom.

Also, be sure that you're doing that in a "live" event like on.

Upvotes: 2

Vitthal
Vitthal

Reputation: 546

Each Function is not necessary.............

$(".tbl-grid tr:odd") selects all the matching 'odd' under .tbl-grid rows

$(".tbl-grid tr:odd").addClass("odd"); is Enough

Upvotes: 0

Sergio
Sergio

Reputation: 6948

$('table tr').removeClass("odd").removeClass("even");
$('table tr:odd').addClass('odd');
$('table tr:even').addClass('even');

Upvotes: 0

Related Questions