Utilizing Rails nested model forms for automatic loading instead of manual clicking

I have a function that adds a nested form when clicked, and it is working perfectly.

$(document).on 'click', 'form .add_fields', (event) ->
  time = new Date().getTime()
  regexp = new RegExp($(this).data('id'), 'g')
  $(this).before($(this).data('fields').replace(regexp, time))
  event.preventDefault()

However, I need this function to also trigger once on page load and then continue to work when clicked. To achieve this, I added the following code:

$(document).on 'click', 'form .add_fields', (event) ->
  time = new Date().getTime()
  regexp = new RegExp($(this).data('id'), 'g')
  $(this).before($(this).data('fields').replace(regexp, time))
  event.preventDefault()

$(document).on 'load', 'form .add_fields', (event) ->
  time = new Date().getTime()
  regexp = new RegExp($(this).data('id'), 'g')
  $(this).before($(this).data('fields').replace(regexp, time))
  event.preventDefault()

After adding the onload event as described above, the function doesn't trigger on page load. However, the click event still works correctly and adds the nested forms. How can I fix this issue?

Answer №1

Alright, your current event setup is not quite right; you need to include page:load instead of just using load, especially because of turbolinks. Additionally, there seems to be some repetition in your code. Here's a more efficient implementation for you:

addNewNestedItem = ->
    $('form .add_fields').on 'click', (event) ->
        time = new Date().getTime()
        regexp = new RegExp($(this).data('id'), 'g')
        $(this).before($(this).data('fields').replace(regexp, time))
        event.preventDefault()

$(document).ready addNewNestedItem
$(document).on 'page:load', addNewNestedItem

The above code snippet is guaranteed to work effectively and it is elegantly structured.

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

sending information back to the controller with get method (ajax, javascript)

I'm currently facing a challenge where I have an event listener waiting for a button to be pressed. Once the button is pressed, the controller method 'update' is called which then triggers the view method 'input' to fetch data from ...

Unable to See Success Notification on First Attempt

I am facing an issue with displaying a message when adding a new record. The first time I add a record, the message shows up correctly. However, if I try to add another record, the message does not appear even though the record is added successfully. Here ...

Is there a method to include query parameters in a middleware and transfer them to the server router in Next.js?

Next.js version 12.2.5 I attempted to use a URL object for adding query parameters as mentioned here, but it did not work as expected. Is there a method to include query parameters in a middleware that can be accessed using useRouter() on the server side ...

Transferring data to a view

I have a dilemma with handling user selections from a select option list and a jstree object in Django. My goal is to pass these choices to a Django view for processing and obtain a response. I've encountered an issue where the template fails to load, ...

Using Vue.js for displaying strings with line breaks

I'm struggling to include a line break in string interpolation within my printed HTML this.externalUsers = data.externalUser.map(element => `Name: ${element.firstName} ${element.lastName}\n <br><br />Email: ${element.email}`); In ...

I have a string in base64 that contains = symbols. What is the best way to remove them from the

What is the best method for removing "=" characters when concatenating base64 strings? I transmitted a byte stream[] of data from the servlet as an http response, and on the client side I am attempting to open the pdf viewer. However, I am unable to view ...

utilizing ng-option to present choices in a dropdown menu

I have been implementing a scroll-down menu in my application using options. However, I now want to switch to using ng-option to populate the values from a JavaScript file. I also require assistance with writing AngularJS code for this task. Below is a s ...

What is the proper way to avoid syntax errors when inserting HTML strings into an Iframe?

My Current Project: Currently, I am storing formatted text in a MySQL database with the following structure: I'm Robert (I'm = I am)<br>You're in France (You're = You are)<br><br><strong></strong><span ...

Tips for calculating the cumulative values from various documents within a collection and transferring the total sum to a separate document in another collection

In my current project, I am working with recipes and ingredients. Each of these entities has its own model and controller. A recipe can have multiple ingredients and the calorie amount of each ingredient is stored in the "calories" field. The main challeng ...

Different methods for modifying the height of an Angular datatable in response to the data provided

Encountering an issue with adjusting the height of a datatable when calling a webservice to populate it. A webpage features a collapsible div element alongside a datatable. Upon collapsing the div, the table's height is calculated and resized using i ...

Using Cytoscape.js to showcase Java-generated nodes

I am exploring how to generate a graph using data produced on the server side of my Java EE application. Specifically, I am wondering about the process of inserting a data structure (JSONObject) into the "elements" section in the code snippet below: $(fun ...

Is there a way to switch from a tab that is being called to the tab that made the call

Imagine you're using a cutting-edge tabbed browser. If you have a page open in one tab that links to another page in a different tab What's the best way to switch from the second tab back to the first tab? Is there an easy way to return to ...

Is it possible to integrate external search functionality with Vuetify's data table component

I am currently working with the v-data-table component from Vuetify, which comes with a default filter bar in its properties. This table retrieves data from a local JSON file. The issue arises when I have another external component, a search bar created u ...

How can I utilize the mapv tool created by Baidu in a Node project?

I need assistance converting the following code to a node environment. The code can be found at Here is the code snippet: var map = new BMap.Map(slice.selector, { enableMapClick: false }); // Create Map instance map.centerAndZoom( ...

Create a gulp task within a callback function that is initiated by calling the filesystem.readdir

When attempting to read the name of the first folder from a directory, and then defining gulp tasks based on that folder, I am encountering an issue. Specifically, after defining a task inside the callback function, the tasks do not get properly defined. T ...

Waiting for the response to come by subscribing in Angular

I am encountering an issue while trying to subscribe to an Observable and assign data from the response. The problem is that my code does not wait for the response before executing the console.log(this.newIds) line, resulting in an empty value being logg ...

Arranging and Using Mongoose.js to find and remove a single item

According to the Mongoose.js documentation, it should be feasible to apply a sorting directive to methods directly passed to the database such as findOneAndUpdate or findOneAndRemove. In my attempt to select and delete a single document that meets a certa ...

JSON object name

Here are the specific file locations for loading each of the CSS and JS files. <link href="css/default.css" rel="stylesheet" /> <script src="js/main.js"></script> In XML, the filename is input as shown below ...

Is there a way for me to pinpoint the location of an error in React?

Currently, I am operating a basic React application with webpack in development mode by using the following command: webpack -w --mode development --config ./webpack.config.js This setup ensures that my code remains unminified. However, I am encounterin ...

Why is the JSP command <%=%> getting overlooked within a Javascript statement located inside a taglib tag declaration?

Allow me to provide an example to make this concept easier to understand! The jsp file... <%@ taglib prefix ="jam" uri= "http://jam.tld" %> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="ISO-8859-1"%> <% ...