Javascript function is only triggered after 2nd button click

Asked

Viewed 185 times

0

When you click on a button to delete an item from a list using Javascript, it only executes the action after the 2nd click. I would like to know what I must do to make the function work correctly from the 1st click.

Modal bootstrap

<!-- Modal - remover estado do serviço -->
<div class="modal bd-example-modal-sm" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="exampleModalLabel">Deseja remover este estado do serviço?</h4>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-danger" id="btn-remover-estado" onclick="return removerEstado();">Sim</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">Não</button>
            </div>
        </div>
    </div>
</div>

Javascript function

function removerEstado(){
    $('#btn-remover-estado').click(function(){
        let estados = document.getElementById('lista-estados');
            estados.remove(estados.selectedIndex);
    });
}
  • 2

    Victor, apparently you still don’t understand how events work in javascript. When you say onclick=uma_funcao() you are saying to perform that function when the element is clicked. When you do $('#meu-id').click(uma_funcao) you are doing the same only in a different way. I explain better about events and jQuery in this answer, if interest.

  • Yes, Fernando. My javascript skills are still very low. I will take advantage of the answer you gave me to understand more about this topic. Thank you.

2 answers

3


This is because by clicking the first time you call the function removerEstado() and calls the click function, in the second the function has already been called and the click function can be used.

The right thing to do.

$('#btn-remover-estado').click(function(){
    let estados = document.getElementById('lista-estados');
    estados.remove(estados.selectedIndex);
});
<button type="button" class="btn btn-danger" id="btn-remover-estado">Sim</button>

Or

function removerEstado(){
    let estados = document.getElementById('lista-estados');
    estados.remove(estados.selectedIndex);
}
<button type="button" class="btn btn-danger" onclick="return removerEstado();">Sim</button>

1

What is happening is this, you are creating your button with the attribute onclick passing a function:

<button type="button" onclick="return removerEstado();">Sim</button>

In his job removerEstado every time she is called, another event of onclick (jQuery.click).

That is to say:

1 vez clicado 
  chama removeEstado, Ela adiciona um evento de click pelo jQuery
2 vez clicado 
  chama removeEstado, Ela adiciona outro evento de click pelo jQuery
  chama em cascata os eventos adicionados pelo jQuery
    ou seja 1 e 2
3 vez clicado
  chama removeEstado, Ela adiciona outro evento de click pelo jQuery
  chama em cascata os eventos adicionados pelo jQuery
    ou seja 1 2 e 3.

For you to understand what is happening I simplified your code, see/run it below:

var count = 0;
function removerEstado(){
    console.log('removerEstado()');
    
    /// ; Pega o elemento pelo ID e adiciona um evento de `onclick`
    $('#btn-remover-estado').click(function(){
        console.log(++count);
    });

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<button type="button" class="btn btn-danger" id="btn-remover-estado" onclick="return removerEstado();">Sim</button>

Browser other questions tagged

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