There is my training project on ruby. I do editing objects using JS. Now it works like this: Edit the first time - everything is fine. Without refreshing the page, I press edit and you can see that the object is rereading, but the form for editing does not appear. I press the third time - everything is fine (Like the first time).

Here is the link to my js code - my repository. Here is this code.

$('.edit-answer-link').click(function(e) { e.preventDefault() $(this).hide() answer_id = $(this).data('answerId') $('form#edit-answer-' + answer_id).show() }); 

Down there is:

 $(document).ready(ready); $(document).on('turbolinks:load', ready); $(document).on('page:update', ready); 

    1 answer 1

    click event only for items that satisfy the selector currently on the page.

    I would venture to suggest that the problem is that when submitting the form, HTML is updated, which leads to the fact that the old bandages will no longer work for the updated elements. Those. fulfills the default behavior, and this is a link. Clicking on an empty link means updating the page. On the updated page, the events will be reloaded again before the HTML update.

    To intercept events for new items, use on :

     $('body').on('click', '.edit-answer-link', function(e) { e.preventDefault() $(this).hide() answer_id = $(this).data('answerId') $('form#edit-answer-' + answer_id).show() }); 

    Similar question .

    • Changed to on - the same. It is not clear why - Denis Bogatyrev
    • It is not clear why it works out normally - Denis Bogatyrev
    • $ ('. select-best-answer'). click (function (e) {e.preventDefault (); var answerId = $ (this) .data ('answerId'); var answerSelector = 'div [data-answer- id = '+ answerId +'] '$ (answerSelector) .replaceWith ("<% = j render @answer%>");}); ps By habit I press Enter and the comment closes. Excuse me. - Denis Bogatyrev
    • @DenisBogatyrev, fixed an example - anoam
    • It worked. Thank you. - Denis Bogatyrev