jquery - Generate dynamic ID's for each accordion button

admin2025-06-03  3

Hello my awesome WP peeps. I have a situation where I have an accordion and I want to add a show/hide all button for each new accordion I add.

So I'm able to generate the post ID in the admin for each new button like:

 <button id='wp_1'></button>

Im also able to add the jQuery code for an onclick event that will open the accordion like:

$('#wp_1').on('click', function () {
            $('.panel-collapse').collapse('toggle');
        });

The problem is, Im not sure how to generate multiple dynamic ID's so that each button only opens up the accordion below it. So in the screenshot below, how do I get WP to also generate an onlclick for #wp_31? Appreciate the help.

Hello my awesome WP peeps. I have a situation where I have an accordion and I want to add a show/hide all button for each new accordion I add.

So I'm able to generate the post ID in the admin for each new button like:

 <button id='wp_1'></button>

Im also able to add the jQuery code for an onclick event that will open the accordion like:

$('#wp_1').on('click', function () {
            $('.panel-collapse').collapse('toggle');
        });

The problem is, Im not sure how to generate multiple dynamic ID's so that each button only opens up the accordion below it. So in the screenshot below, how do I get WP to also generate an onlclick for #wp_31? Appreciate the help.

Share Improve this question asked Feb 17, 2019 at 18:39 captainMcaptainM 217 bronze badges 2
  • If you call your accordeon in a loop you could be able to manually set a unique id with a simple icrementation. Can you post us the code on yhe frontend? – Patrice Poliquin Commented Feb 17, 2019 at 23:30
  • @PatricePoliquin, thanks. I figured a way to do it with jQuery without adding multiple onclick calls. Ill post the answer shortly. – captainM Commented Feb 19, 2019 at 6:22
Add a comment  | 

1 Answer 1

Reset to default 0

I was able to solve this problem with using the jQuery closest method.I had to nest the button inside the container so the function would be able to return the first ancestor of that particular button element that is clicked.

$(".toggle-button").on("click", function() {
  $(this).closest('.collapse-group').find('.wpsm_panel-collapse').collapse('toggle');
});
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748887667a314551.html

最新回复(0)