Home > OS >  Merge $var positions in a loop with PHP
Merge $var positions in a loop with PHP

Time:05-06

I have this PHP that is helping me populate a script:

<script>
(function($){

    <?php foreach($buttons as $button) { // loop throught all available buttons ?>

    // by clicking button one
    $('.button-1').click( function () { 
        // display:none to all filters but filter-1
        $('.filter-2, .filter-3, .filter-4, .filter-5, .filter-6').css({display: "none"});
        // guarantee filter-1 will be visible with display: block;
        $('.filter-1').css({display: "block"});
    });        
            
    <?php } ?>

})(jQuery);
</script>

But the numbers of buttons and filters (button-1, filter-2, and etc) are currently manually set, and I don't know how to build the logic, where

  • First iteration? Set 'button-1', set display:hide to all filters but 'filter-1' and display:block only to 'filter-1'
  • Second iteration? Set 'button-2', set display:hide to all filters but 'filter-2' and display:block only to 'filter-2'
  • And so on until foreach is over

How can I build this logic?

CodePudding user response:

Don't do it in a loop. Give all the buttons a common class button, and add a handler to all of them. This can then get the specific button number from an attribute, and use that in the code to determine which filter to display.

So the HTML for the buttons will be something like this:

<button  data-filter="1">Filter 1</button>
<button  data-filter="2">Filter 2</button>
and so on

and the HTML for the filters will be:

<div >blah</div>
<div >lorum ipsum</div>
and so on

Then your jQuery code will simply be

$(".button").click(function() {
  let filternum = $(this).data("filter");
  $(".filter").hide();
  $(`.filter-${filternum}`).show();
}

This adds the handler to all the buttons at once.

  • Related