How to simulate button click on jQuery?

Asked

Viewed 123 times

0

I have a function that performs by clicking a button on jQuery.

    $('.btnEntrega').click(function (e) {=
     idPrograma = $(this).data('id');

     CoresFormasPlacas($(this).data('placa'), $(this).data('especie'), $(this).data('categoria'), $(this).data('tipo'));

     $('#modalConfirmaEntrega #exampleModalLongTitleAuto').html("<br/> Autorização: " + $(this).data('autorizacao'));
     ConfirmaEntrega("Confirma a Entrega?");

     e.preventDefault();
     e.stopPropagation();

 });

I wish that when another button was clicked, it would call that same function, so I did the following:

$('.btnDigital').click(function () {
  $(".btnEntrega").click();
});

But it doesn’t work, and it doesn’t make any mistakes. How do I call the top function when the "btnDigital" button is clicked?

  • have tried: $('#botao').trigger('click');

  • I tried, but it didn’t work

2 answers

1


Well, I would create a function for the code you want to run by the two buttons. It is not a good idea to make one button depend on the other, because if one ceases to exist the other stops working, among other architectural factors.

Try it this way:


function entrega(object) {
     idPrograma = object.data('id');

     CoresFormasPlacas(object.data('placa'), object.data('especie'), object.data('categoria'), object.data('tipo'));

     $('#modalConfirmaEntrega #exampleModalLongTitleAuto').html("<br/> Autorização: " + object.data('autorizacao'));
     ConfirmaEntrega("Confirma a Entrega?");
}


$('.btnEntrega').click(function (e) {=
     entrega($(this));

     e.preventDefault();
     e.stopPropagation();

 });

$('.btnDigital').click(function (e) {
     entrega($(this));

     e.preventDefault();
     e.stopPropagation();
});

0

To trigger automatic events: Trigger / triggerHandler.

$('.btnDigital').click(function () {
    $(".btnEntrega").trigger('click');
});

Documentation jQuery.

  • I tried yes, but as far as I know . Trigger('click') is just a shortcut to . click() so the error keeps occurring.

  • Trigger is not a click shortcut, the function trigger() forces an event simulating a certain function, such as "click" without the user’s action, remembering that some events are blocked, by security rules in the browsers, and that in turn are prevented from being triggered automatically, depending on the risks, but since you are running a click function, manually, I believe this rule is permissive.

  • I got it, I’ve used Trigger several times, but in this case it didn’t work. The @Boolean solution was the one that worked for me...

  • The @Boolean solution makes perfect sense, since you are just inheriting to another button the same action, it would be smarter to create a method that can be called, You can improve this by using a class, it is always better to work with inheritance and polymorphism.

Browser other questions tagged

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