Rails and JavaScript: Changes made to the HTML on the page no longer trigger the UJS .change() function

I have successfully implemented a rendering partial with UJS, but there's a problem:

The partial is able to update the form's markup that triggers the onchange action. However, the JavaScript on this newly updated markup stops working.

As a result, the code works only once and then fails to work again.

I suspect that the UJS binding occurs during the initial loading (document.ready), but not on the elements updated by the partial.

--> How can I bind the same action to the new markup returned from the ajax request? --> Is it feasible to re-trigger the "binding" of the UJS function as done during the document load? Do I need to create an additional 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
    });
}

Answer №1

A more streamlined solution involves utilizing the event listener on in place of change.

Here is an example of how the JavaScript code would look:

$(document).ready(function() {

  $('select.auto_update').on('change', (function(){ 
    ...
    $(this).closest("form").submit();        // won't be triggered on fresh markup
  });
 });

This approach includes two key modifications:

  1. Using on instead of change
  2. Submitting the form without specifying a selector.

By implementing this method, your event will remain active, eliminating the need for creating a custom function for ready.

Answer №2

To tackle this issue, I developed an external function that serves the purpose of:

  • being executed once upon loading of the document
  • being triggered each time the markup undergoes updates

Here is the code snippet:

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

/* This function reassigns the appropriate event listeners to the markup. It is invoked every time the markup is refreshed to ensure proper binding of the listeners. */
function execute_auto_update() {
    /* Automatically update the URL when any select element within the breadcrumbs section has its value changed */
    $('select.auto_update').change(function(){ 
        $('#breadcrumb_point_id').val($(this).val());
        $(this).submit();
        console.log("Auto update functionality activated");
    });

    /* Update the content of the main div with the received markup from the server */
    $("#breadcrumb_form").bind('ajax:complete', function(status, data, xhr){
        $("#loopview_content").html(data.responseText);
        execute_auto_update();
        console.log("Main div content (loopview_content) updated as a response to ajax request (breadcrumb navigation)");
    });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

React with TypeScript: The children prop of this JSX tag is specifically looking for a single child of type ReactNode, but it seems that multiple children were passed instead

For my class project in APIs, I am using react-typescript but running into issues. My problem arises when attempting to loop through an array of "popular" movies using .map. However, I keep getting this error message: "This JSX tag's 'children&ap ...

Error importing React Icons with the specific icon FiMoreHorizontal

Currently following a guide to create a Twitter-like application and I need to add the following imports: import { FiMoreHorizontal } from 'react-icons/fi' 2.3K (gzipped: 1K) import { VscTwitter } from 'react-icons/vsc' 3.1K (gzipped: ...

What is the best way to display a child element in the right panel?

Hello, I need help in displaying child elements next to the parent element. My function works fine the first time, but fails the second time. Here are the steps I followed: 1) Clicked the Add button 2 times, generating row2 as well as a submenu of firs ...

`We enhance collaboration within sibling next components by exchanging information`

Completely new to web development, I have been working on an app with a navbar that allows users to select items from a drop-down menu. My specific issue is trying to access the title.id in a sibling component, but it keeps coming up as null. PARENT COMPO ...

What steps can be taken to prevent the Google search bar from adjusting focus in a Chrome extension?

Currently, I am in the process of developing a Chrome extension that incorporates some of the key functions from the vimperator plugin on Firefox. One issue I am facing is capturing keystrokes before a webpage does. An example of this difficulty can be se ...

The total of a collection of values stored within a property nested within the main object

{ 'Amelia L. Jones': [ // o { author: 'Amelia L. Jones', likes: 7 }, { author: 'Amelia L. Jones', likes: 3 } ], 'Raymond T. Hayes': [ { author: 'Raymond T. Hayes', likes: 9 }, ...

Dealing with Array Splicing Issues in Angular

Being fairly new to the world of AngularJS, I suspect that I am just making a simple mistake. My goal is to splice the cardTypes array at the var newCard = cardTypes.shift(); line rather than using .shift() so that I can consider my ng-repeat index. Whil ...

Error handling in AngularJS and Firebase Promises

I am currently following a tutorial on thinkster.io and encountering some issues. The tutorial uses a deprecated SimpleLogin, so I have made the necessary code changes. However, I keep running into an error that says: TypeError: Cannot read property &apo ...

Mastering div manipulation with jQuery: A step-by-step guide

I have three divs with the classes "col-md-2," "col-md-8," and "col-md-2." What I want is that when a button in the "col-md-8" div is clicked, both of the other divs should be hidden and the "col-md-8" div should expand to occupy the full width of "col-md ...

How to create a resizable dialog box with dynamic height using

I need assistance with dynamically adjusting the height of a jQuery UI Dialog based on its contents. Below is my current code snippet: $( "#dialog-modal_"+productID ).html( "<iframe src='index.php?act=showProduct&amp;id="+productID+"' wi ...

Navigating JSON data through drilling techniques

There is an API available at this link: I'm struggling to filter the data specifically for objects marked as potentially hazardous asteroids. How can I modify my jQuery Ajax code to achieve this without getting an 'undefined' result? $(doc ...

Maintaining the position of the screen as you type in information that is located outside of the container

I am encountering an issue with the input/text-area element in absolute position extending halfway outside the container. The screen position seems to follow the caret as I type, but I'd prefer to keep writing and have part of the text hidden beyond t ...

save the received data to a new document

How can I pass the data returned from the API below to another function in a separate JavaScript file? This question may be similar to others, but those do not involve working with returned results. Please consider this before labeling it as a duplicate. ...

problem encountered while attempting to transmit data to multer in React

I was attempting to upload an image to the backend using Multer. I have reviewed the backend code multiple times and it appears to be correct. Could there be an issue with my front-end code? Here is a POST code snippet: const response = await fetch(' ...

Is there a Javascript database that functions seamlessly on Android, IOS, and Windows Phone 8 (Internet Explorer 10)?

I am currently maintaining an app for Android, iPhone, and Windows that relies on an ASP.NET Server with SQL Server Database. I would like to make the app functional offline as well, which requires utilizing a database on the client side. Despite my best ...

Null value added to MySQL database using Node.js

app.post('/addBeer', (req, res) => { pool.getConnection((err, connection) => { if (err) throw err console.log('connected as id' + connection.threadID) const params = req.body var name = params.n ...

Elevate when the mouse hovers over the button

My current task involves increasing the bottom-padding of a span when the mouse hovers over a button. Here is the button code: <button class="btn btn-success btn-circle" id="myBtn" title="Go to top"> <span id="move" class="fa fa-chevron-up"&g ...

Is there a way to retrieve the name of a JSON or obtain the file path using NodeJS Express Router?

I've been experimenting with adding a named routers feature to the Express router for my NodeJS project. I managed to implement it successfully, but there's one thing I'm stuck on... the path. Specifically, when I have a route setup like thi ...

What is the largest file size that JavaScript is capable of processing?

Similar Inquiry: Javascript Memory Limit Currently, I am in the process of constructing an HTML page using client-side JavaScript that aims to load a significant XML data file weighing around 150mb upon page initialization. Initially, when the file si ...

Having trouble incorporating autocomplete search results into an HTML table using Jquery, Ajax, and JSP

My current project involves an App that utilizes AJAX with jQuery to communicate with a Spring-boot REST controller. While the app is functional, I am facing difficulty in displaying the search results neatly within HTML tables. https://i.sstatic.net/7sw8 ...