saltyalty saltyalty - 4 months ago 10
Javascript Question

How to make specific li's under a button appear when button is clicked

First off just want to mention I'm very new to coding and I know my code isn't the most efficient, I'm just experimenting. Now to the question!

I have an EJS file that talks to a NodeJS proxy, which sends it JSON data to manipulate (hope I said that right). The code below is working fine for me, the only problem that I am having is that when I click on one button it unhides all the li's, instead of just the li's under the button I clicked. It's very hard to assign classes and then write JavaScript code for each class generated, because I don't know how many buttons there will be in the first place.

I currently have:

Javascript (jQuery) Code

$(document).ready(function(){
$('button').on('click', function(){
$('li').toggleClass('hide');
});
});


HTML/EJS Code

<% for (i = 0; i < sortedStackName.length; i++) { %>
<% if (sortedStackName[i] == sortedStackName[i + 1]) { %>
<% } else { %>
<button class="btn btn-primary space" id="<%= %>"><%= sortedStackName[i] %></button>
<% data3.forEach(function (provider) { %>
<% if (provider['stack_name'] == sortedStackName[i]) { %>
<a href="#"><li class="hide"><%= provider['service_name'] %></li></a>
<% }}); %>


Some posts I've read that haven't worked:

jQuery display nested ul on click of div in parent li

how to make text appear when a button is clicked

How to make a view appear through animation when a button is clicked?

Trying to make a div appear when a button is clicked

Answer

Since the number of <a> tags is variable, I think placing them in a <div> and then toggling class for that div is a cleaner solution, and you can use Ashkan's suggestion there as well. So your EJS will look like:

<div class="hide">
<% data3.forEach(function (provider) { %>
<% if (provider['stack_name'] == sortedStackName[i]) { %>
<a href="#"><li><%= provider['service_name'] %></li></a>
<% }}); %>
</div>

And in JQuery:

$(document).ready(function(){
   $('button').on('click', function(){
        $(this).next('div').toggleClass('hide');
    });
});

Let me know if that works.

Comments