button in a div with display: None does not receive jQuery event when it is embedded in another div

Asked

Viewed 28 times

1

I have 2 div's

One getting the contents of the other:

$( "#conta" ).html( $( "#escolhaMembro" ).html()

to #escolhaMembro is with display: none.

When the contents of #escolhaMembro appears in the body within the #conta, also comes a button.

That one button is not receiving the event of jQuery

// JavaScript Document
$(document).ready(function (e) {

    $("#buttonCadastrarCelulaMembro").on("click", function () {
...

What’s the problem here?

  • You could try playing the code on a fiddle ?

1 answer

1


When copying the HTML from one div to another, you will be duplicating the button with the same id. Depending on the order of the elements, the event will only be triggered by clicking on the first button with the duplicated id. That is, if the button with the same id whatever is in the hidden div, the event will not be triggered by clicking the other visible button. This is one of the reasons it is wrong to duplicate id’s, because Javascript will only consider the first in order.

What you need to do is change the id for class, because one or more elements may have the same class, but not the same id.

$(document).ready(function (e) {
   
   $( "#conta" ).html( $( "#escolhaMembro" ).html() );

    $(".buttonCadastrarCelulaMembro").on("click", function () {
       
       console.log("botão clicado");
       
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="escolhaMembro" style="display: none;">
   <button class="buttonCadastrarCelulaMembro">Botão</button>
</div>
<div id="conta"></div>

  • Thank you so much @SAM.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.