Calling Javascript function with onclick with content loaded from div

Asked

Viewed 27,528 times

2

I have a div that has its contents loaded after loading the rest of the page. It is called by a button via AJAX. I have another button inside that content that would call a Javascript function to confirm page targeting. But when it is inside the contents pressed the button does not work.

Follow the function code.

<script language="Javascript">

function confirmacao(aluno) {
     var resposta = confirm("Deseja remover esse aluno?");

     if (resposta == true) {
          window.location.href = "del_aluno_done.php?aluno="+aluno;
     }
}
</script>

Follow the button code

<a href='javascript:func()'onclick='confirmacao('$aluno;)'>
  • 2

    I would start by arranging the link (button). Since it will confirm, call function func() from within function confirmation, if necessary.

  • You got this thing to work?

  • Hello... Dude, did you make it work? I understood your problem, and I’m going through it. I need to make a call from a button, after being pressed via ajax.

1 answer

2

Your code has some errors. I do not know if it was in a hurry to put/simplify the example, or if you have errors in your code even.

Once you’ve joined the jQuery tag here’s a hint taking all the javascript out of your HTML.

1 - Classify the button
2 - If you call it a button, it might be a good idea to use a <button> instead of a <a> mainly because there is no link to clickar, only a javascript behavior that should be run...
3 - Information, possibly passed via PHP, that refers to this element can be stored in a field data-

So, in time for

<a href='javascript:func()'onclick='confirmacao('$aluno;)'>

Can use

<button type="button" data-aluno="<?php echo $aluno; ?>" class="botaoAluno">Clique aqui</button>

And in Javascript/jQuery

$(document).ready(function(){
    $(document).on('click', '.botaoAluno', function(){
        func();
        var aluno = $(this).data('aluno');
        var resposta = confirm("Deseja remover esse aluno?");

         if (resposta == true) {
              window.location.href = "del_aluno_done.php?aluno=" + aluno;
         }
         // ou pode manter a funcao à parte e chamar `confirmacao(aluno);` aqui dentro
    });
});
  • When I click the button, nothing happens. When I try to call the function from inside the div that was loaded after the rest of the page, it doesn’t work.

  • @user3127841, add your HTML to the question so I can adjust the answer. Without HTML it’s hard to get it right more than I did.

  • I have no way to answer my own question =/ but I copied what you sent here, is why is being loaded the content of the div that has the button, after the rest of the page?

Browser other questions tagged

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