Question

I have a working rendering partial with UJS, but :

The partial is updating the markup of the form that triggered the onchange action, then, the javascript is not triggered anymore on this newly updated markup.

The code here under is thus working ONE time, and then not anymore.

I think the UJS binding to the is done at first loading (document.ready), but not on the elements that the partial updates

--> How to bind the same action on the new markup coming back from the ajax request ? --> Is it possible to trigger again the "binding" of the UJS function as when the document is loaded ? Do I need to create an extra function ?

Markup:

<form action="/loopview/1/show" data-remote="true" id="breadcrumb_form" method="post">
  <select class="auto_update">
   <option value="1970" selected="selected">test</option>
  </select>
</form>

UJS :

$(document).ready(function() {
    ...
    $('select.auto_update').change(function(){ 
        ...
        $(this).submit();        // never triggered on newly loaded markup
    });
}
Was it helpful?

Solution

Another simple solution is to use event listener on instead of change.

Then the JS code is like this:

$(document).ready(function() {

  $('select.auto_update').on('change', (function(){ 
    ...
    $(this).closest("form").submit();        // never triggered on newly loaded markup
  });
 });

Two changes:

  1. on to replace change
  2. submit the form but not selector.

This way your event will always live, save your cumbersome to build custom function for ready.

OTHER TIPS

I solved it by creating an external function that is called :

  • once when the document is loaded
  • each time when the markup is updated

Code :

$(document).ready(function() {
    ... 
    bind_auto_update_action();
});



/* (Re)associate the correct event listeners to the markup. Is called at each refresh of the markup to (re)bind the listeners. */
function bind_auto_update_action() {
    /* Auto update the url when changing the value of one of the select in the breadcrumbs */
    $('select.auto_update').change(function(){ 
        $('#breadcrumb_point_id').val($(this).val());
        $(this).submit();
        console.log("Auto update function ");
    });

    /* Update the content of the main div with the returned markup from the serveur */
    $("#breadcrumb_form").bind('ajax:complete', function(status, data, xhr){
        $("#loopview_content").html(data.responseText);
        bind_auto_update_action();
        console.log("Update of the loopview_content <div> due to ajax response (breadcrumb navigation)");
    });
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top