Mehar
Mehar

Reputation: 2228

Adding class using jQuery in Foreach loop

I am running jQuery script in foreach loop to add classes in html dynamically.I want to add two different classes on different event status but it adds both the class, the class in the if condition and class in else condition.

Here is my code

<?php foreach( $events as $event ){ 
if ($event->status=='new'){ ?>
jQuery( ".upcoming-events" ).addClass( "new_event" );   
<?php } 
else {
?>
jQuery( ".upcoming-events" ).addClass( "old_event" );
<?php } } ?>

but it adds both the classes in upcoming-events div.

any hint???

Upvotes: 0

Views: 559

Answers (3)

Sathish M
Sathish M

Reputation: 37

You may use Mrinmoy's, but here is more simplyfied,

<?php 
foreach( $events as $event ){
if ($event->status=='new'){ 
?>
jQuery( ".upcoming-events" ).removeClass( "old_event" ).addClass( "new_event" );
<?php 
} else { 
?>
jQuery( ".upcoming-events" ).removeClass( "new_event" ).addClass( "old_event" );
<?php 
} } 
?>

Upvotes: 1

Nebojsa Susic
Nebojsa Susic

Reputation: 1260

".upcoming-events" selector select all elements with upcoming-events class, so if you have any new event you will add new_event class to ALL elements, not only current one.

You must select elements by id, par example.

Upvotes: 1

Mrinmoy Majee
Mrinmoy Majee

Reputation: 376

Check my code for your answer

<?php foreach( $events as $event ){
if ($event->status=='new'){ ?>
jQuery( ".upcoming-events" ).removeClass( "old_event" );

jQuery( ".upcoming-events" ).addClass( "new_event" );
<?php }
else {
?>
jQuery( ".upcoming-events" ).removeClass( "new_event" );
jQuery( ".upcoming-events" ).addClass( "old_event" );
<?php } } ?>

Upvotes: 1

Related Questions