0

I have an option to refresh this DIV after click a button inside that DIV

<div class="col-md-12" id="reloadedit" >
    <div class="block">
        <div class="block-header block-header-default">
             <h3 class="block-title">Edit Language</h3>
        </div>
        <div class="block-content" >
        <?php
        DoThisFunction($link);
        ?>
        </div>
  </div>
</div>
</div>

I've also created a simple function to refresh the div:

<script>
function updateDiv()
{ 
    $("#reloadedit").load(location.href + " #reloadedit>*", "");
}
</script>

Everything inside that DIV is PHP generated. The function works very well and refresh that DIV with the updated function.

I have 2 problems:

  • After the first refresh, any buttons inside that div doesn't work. Basically, I click a button that does a task (for example activate ID X). It processes everything fine and refresh that div and show as active. If I click the button again (to disable), it doesn't do anything. (Please note those actions are made with sweetalert and jquery calls).

  • How can I make an universal function so I can call it everytime I need to refresh a div (like using updateDIV("#DIVNAMEHERE"))?

Thanks in advance.

Edit: My code that get the buttons click is:

$("button").click(function() {
let button = $(this); // the button you clicked
let id = button.data("id"); // the data-id attribute of the button
let func = button.data("function");
if(func == "publish"){
    Publish(id);
}
});
Tiago
  • 625
  • 5
  • 16
  • 1) Use delegated event handlers on the buttons. See the duplicate for more information 2) Use a function with an argument - exactly as your example shows. – Rory McCrossan Aug 29 '18 at 14:15

1 Answers1

1

When you refresh the content inside the div you are removing all of the event listeners attached to the elements inside.

Since you are dealing with dynamic content you need to use event delegation.

Change your event handler:

$("button").click(function() {
    //Code
});

To this format:

$('#reloadedit').on( "click", "button", function(e) {
    e.preventDefault();
    //Code
});

This would trigger the click event handler when any button inside the div is clicked.

Jackson
  • 3,476
  • 1
  • 19
  • 29
  • Sorry but I can't understand it. My knowledge in JS/jQuery is reduced so I'm getting trouble to understand it. I've edited my main question and added the code that "reads" when the button is clicked. Can you clarify me please? – Tiago Aug 29 '18 at 14:37
  • No problem, I have updated my answer – Jackson Aug 29 '18 at 14:47