Search code examples
javascriptjqueryadvanced-custom-fieldsslidetoggle

Trying to hide/show a div however .slideToggle() is applying to all divs on page - Advanced Custom Fields Repeater


I have a hidden div that I want to show on a button press however because the ACF repeater is repeating the id it's opening all the hidden divs at once.

//This is inside a repeater field causing the #buy to repeat
    <button id="button">
       <img src="images/right-arrow.png" width="35" class="button__icon">
    </button>
    </div>
    <div id="buy" style="display:none" class="tour-event__wrapper--hidden tour-event__wrapper--hidden-bottom">
      <div class="widget-containter">
        <?php the_sub_field('eventbrite_widget'); ?>
      </div>
    </div>


// JQuery 
$('button').click(function () {
  $( "#buy" ).slideToggle("slow");
});

I think I need to find #buy using .find() or .next() however I haven't had much luck using those.


Solution

  • It's possible to get unique IDs on an ACF repeater, which should solve your problem:

    <?php if(get_field('repeater_field_name')): $i = 0; ?>
    <ul>
    <?php while(has_sub_field('repeater_field_name')): $i++; ?>
        <li class="section-<?php echo $i; ?>">
            <button id="button<?php echo $i; ?>">
                <img src="images/right-arrow.png" width="35" class="button__icon">
            </button>
            <div id="buy<?php echo $i; ?>" style="display:none" class="tour-event__wrapper--hidden tour-event__wrapper--hidden-bottom">
                <div class="widget-containter">
                <?php the_sub_field('eventbrite_widget'); ?>
                </div>
            </div>
        </li>
    <?php endwhile; ?>
    </ul>
    <?php endif; ?>
    

    Source

    Your jQuery snippet would then be

    $('[id^=button]').click(function(evt) {
        var buyId = evt.target.id.replace("button","buy");
        $("#"+buyId).slideToggle("slow");
    });