Event change of select within Modal ceases to function after reopening it

Asked

Viewed 51 times

0

I have a select inside a modal window that displays or hides an input field according to the option selected by the user. Example: if option=1, it shows the input. if option=2, it hides the input.

Everything works perfectly, until I noticed something curious: when reopening the modal after the previous opening has triggered and changed the value of select several times, I noticed that the show/Hide event stops working.

Obviously, after refreshing the page, it works again.

I tested the unbind, but it didn’t work.

        $('#idDivModal1 .data-pagamento').unbind('show','hide');

View full jquery code:

$('#idDivModal1').on('shown.bs.modal', function() {

    $( "#idDivModal1 #campo_pagamento" ).change(function() {
        var campo_pagamento = $("#idDivModal1 #campo_pagamento").val();

        $('#idDivModal1 .data-pagamento').unbind('show','hide');

        if (campo_pagamento=='Sim') {
            $('#idDivModal1 .data-pagamento').show('fast');             
        } else {
            $('#idDivModal1 .data-pagamento').hide('fast');
        }


    });

I also tested the function below (Hidden.bs.modal), but it also did not work:

 $('#idDivModal2').on('hidden.bs.modal', function(e)
{ 
    $("#idDivModal2 #campo_pagamento").off('change');
}) ;
  • Modal content is loaded via ajax?

  • That’s right.... I noticed that the change event is no longer triggered after the reopening of the modal.

  • Try switching $( "#idDivModal1 #campo_pagamento" ).change(function() for $('body').on('change', "#idDivModal1 #campo_pagamento", function(). To monitor the event change, regardless of whether the html content has been updated via ajax. Remove from the modal event and put on the page onload.

  • Benilson, just the fact that I traded it for $('body'). on('change', "#idDivModal1 #campo_payment", Function() the problem has apparently been solved... I wonder what happened?

  • I removed the modal event as per your instruction, and it works correctly....

  • so I can keep it that way?

  • Yes, this way that I gave you, causes changes in the body of the page to be monitored, if they occur, it automatically updates to monitor the included/modified elements as indicated selector. Have a look at the documentation at https://api.jquery.com/on/.

  • thank you very much. how do I include your comment as an answer to that question?

  • You can answer the question yourself, to leave it as a source of future research.

  • thank you, Benilson!

Show 5 more comments

1 answer

2


Barter

$( "#idDivModal1 #campo_pagamento" ).change(function() 

for

$('body').on('change', "#idDivModal1 #campo_pagamento", function()

Browser other questions tagged

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