0

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???

4
  • 2
    You need to addClass relatively Commented Jul 3, 2014 at 8:11
  • you can use hasClass method of jquery to check for class the n remove and add new class Commented Jul 3, 2014 at 8:14
  • can you please update $events array here Commented Jul 3, 2014 at 8:16
  • That means the $events array has at least one new and one old element. Commented Jul 3, 2014 at 8:20

3 Answers 3

1

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 } } ?>
Sign up to request clarification or add additional context in comments.

Comments

1

".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.

Comments

1

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 
} } 
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.