JQuery: show onclick only works for first button

I want to have more buttons that will show the onclick content. When someone presses any button, all content can appear (toShow). It currently works, but only on the first button. So when someone clicks the first button all content appears, but I need all content to show up when someone clicks on any button on the page. Maybe I need a loop? Thanks for the help.

$(document).ready(function(){
    $("toShow").hide();
    $("#show").click(function(){
        $("toShow").show();
        $("buttonShow").hide();
    });
});

<h1>First element</h1>
<buttonShow>
<button id="show">show</button>
</buttonShow>

<toShow>
content
</toShow>

<h2>Second element</h2>
<buttonShow>
<button id="show">show</button>
</buttonShow>

<toShow>
content
</toShow>

      

+3


source to share


1 answer


This is because you have several of the same IDs. Instead, assign classes, and for any button with a class .show

- the corresponding event handler will fire

<button class="show">show</button>
<button class="show">show</button>
<button class="show">show</button>

      




$('.show').click(function(){
    $('toShow').show();
    $('buttonShow').hide();
});

      

JSFiddle example

+6


source







All Articles