Navigating and targeting a specific new input item within a nested form using Cocoon

Encountering an issue with rendering a collection of options in a nested field due to dependency on a filled-in value in the form.

Suspecting that targeting a new input field with a unique ID for each nested input field may provide the solution, but open to corrections if my assumption is incorrect.

Context

Rendering an order form involves automatically generating the first field of 'order_options' which connects orders and options in a many-to-many relationship. The form includes a field to select a bike_type with specific options related to that bike type. Depending on the chosen bike_type, the form displays a picklist with corresponding options. This part of the program functions correctly.

The Issue

When adding another option via Cocoon's link_to_add_association, users should see the same picklist of options as the bike_type remains unchanged. Additionally, the previously selected option should remain visible (i.e., not cleared). However, in the current setup:

  • The previously selected code gets deleted (to clear the picklist in case the bike_type changes)
  • The newly added nested form does not include any options (possibly because it only uses the bike_type options from the initial form field)

Form

<%= simple_form_for [@bike_store, @order] do |f|%>
...

JavaScript/Ajax

<script>
  // Dynamic bikes
  ...
</script>

Nested Form

<div class="nested-fields">
...
</div>

Order Controller

class OrdersController < ApplicationController
...

The attempted callback:

// Dynamic options for nested form
...

Answer №1

To address the issue, I introduced an object_id for each option related to the bike_type. Following that, I utilized 'cocoon:after-insert' on the added option.

Below is the code snippet depicting the solution.

_order_option_fields.html.erb

<div class="nested-fields row">
          <div class="col col-sm-5"> <%= f.association :option, collection: @options, input_html:{
          value: @all_options.object_id,
          id: "dynamic-options"
          }%> </div>

  <div class="col col-sm-5"><%= f.input :option_quantity %></div>
  <%= link_to_remove_association f do %>
      <i class="fas fa-trash"></i>
    <% end %>
</div>

script

<script >
    $(document).on('cocoon:after-insert', function(e, added_option_form){
      var bike_type = $("#bike_type").val();

      $.ajax({
      url: "/bike_stores/<%= @bike_store.id %>/orders/new",
      method: "GET",
      dataType: "json",
      data: {bike_type: bike_type},
      error: function (xhr, status, error) {
        console.error('AJAX Error: ' + status + error);
      },
      success: function (response) {
      var options = response["options"];
      $(added_option_form.find("#dynamic-options")).html("");
      $(added_option_form.find("#dynamic-options")).empty();
       $(added_option_form.find("#dynamic-options")).append('<option>Select option</option>');
      // console.log(options.length);
      for(var i=0; i< options.length; i++){
        $(added_option_form.find("#dynamic-options")).append('<option value="' + options[i]["id"] + '">' + options[i]["name"] + '</option>');
      }
    }
  });
  });

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

Adjusting the background hue of the 'td' element within an ajax request

When I press a button, an ajax call is triggered below. In this call, I append 'td' elements with values to a table. Specifically, on the line ''</td><td>' + result[i].preRiskCategory +', I am attempting to change ...

jQuery: keeping tabs on the progress of loading requests

I've been on a quest to find a solution for monitoring the data volume in a jQuery .load() request. My goal is to have a dynamic bar that grows as the loaded data increases – essentially a progress bar. This progress bar needs to be tied to the .loa ...

The converted document exported using threejs-usdzExporter does not appear correctly on an iPhone

I loaded a glb file using THREE.js GLTFLoader and then exported it to usdz using USDZ Exporter. When I tried to open it in the browser, it showed up in Safari but didn't appear in ARkit in object mode. Instead, it appeared above my head in AR mode. Th ...

Guide to implementing a personalized filter in AngularJS 1.6

I am struggling with injecting a custom filter, status, into my component. Below is the code for my component: function ClaimsListController(dpClaimsListService) { var ctrl = this; ctrl.claims = null; ctrl.searchCriterion = null; ctrl.l ...

Tips for keeping the scroll position of a bootstrap table when reloading the page

Displayed below is a bootstrap table with specific features. <div class="row"> <table id="question-selection" class="table table-sm table-hover table-wrapper"> <tbody> {% for placer in chapter_questions %} ...

What steps can be taken to delete a cookie when the server cannot be accessed?

Currently utilizing a node.js + express server and managing sessions for users who are logged in. I am curious about how a user can log out if the server becomes unreachable? In the usual method, I would simply call req.logout() on the request object in ...

Why am I receiving an error message stating "undefined is not a function" when trying

I am attempting to create a popover using the Angular UI pop over feature. I have loaded my HTML and compiled it, but when I run my program and click on the star icon (where I display the popover), I receive an error stating that 'undefined is not a f ...

Muting the unused variable alert in JavaScript

Whenever I run my typescript compiler, it always gives me errors about unused variables. In C programming, I would prevent this using the following method: void foo(int bar) { (void)bar; } Is there a similar workaround in JavaScript? ...

What is the way to bypass certificate validation when making a Fetch API request in the browser?

The code snippet below is currently being executed in the browser: const response = await fetch(`${url}`, { method: 'POST', headers: { Authorization: `Basic ${authorization}`, }, body: loginData, }) Upon calling this co ...

Ionic timer binding issue: troubleshooting tips

Recently, I developed a stopwatch factory service that primarily focuses on running. Please disregard the reset and other functionalities as they are not yet implemented. Despite setting up $scope.time to capture timer changes, it doesn't seem to upd ...

Implementing timeAgo with jQuery (or a similar tool) to display the elapsed time since a user (client) accesses or updates a webpage

https://i.sstatic.net/Y7bzO.png Currently, the timer displayed always shows the actual time instead of phrases like "about a minute ago" or "5 minutes ago". I have tried different solutions without success. //timeago by jQuery (function timeAgo(selector) ...

What is the best way to incorporate component-specific CSS styles in React?

This is the layout that I am attempting to replicate (originally from react-boilerplate): component |Footer |style.css |Footer.js In Footer.js, the styles are imported in a very elegant manner like this: import React from 'react'; im ...

Guidelines for populating data with an array

I have the following array: const dataArr = [[15, 14, 5], [16, 10, 2], [17, 6, 13], [18, 4, 8], [19, 7, 4]]; Now, I am populating another array using the above data as shown below: for (let i=0; i<dataArr.length; i++){ newData.push(dataArr[i]); ...

Exploring the world of lighting and shadows in WebGL and Three.js

I'm having difficulty focusing lights on specific targets, specifically the main character, while also darkening the background. Additionally, I'm experiencing issues with the shadows not working properly in my code snippet related to lights and ...

Vue error: Uncaught promise rejection - RangeError: The computed value update has exceeded the maximum call stack size

My computed code snippet: computed: { display: { get() { return this.display }, set(newValue) { this.display = newValue } } }, Attempting to update the computed value from a function in ...

Consistently encountering the message 'Error: timeout of 2000ms exceeded' while using Selenium

Good morning, Currently, I am in the process of learning how to use Selenium with JavaScript (specifically using Mocha). I have created a very basic test that is causing some issues during runtime. Whenever I run the test, a new instance of Chrome opens a ...

Guide on retrieving data parameter on the receiving page from Ajax response call

I am working on dynamically opening a page using Ajax to avoid refreshing the browser. The page opens and runs scripts on the destination page, but before running the script, I need to retrieve parameters similar to request.querystring in JavaScript. Belo ...

How can the printing of content be adjusted when the browser zoom function is activated?

Is there a way to prevent the content from zooming when printing while the browser is zoomed in? The goal is for the printing (using iframe) to remain unchanged even if the browser is zoomed. I attempted: document.body.style.transformOrigin = 'top le ...

Tips for sending JSON data to .js files

I am experiencing an issue here. In locations.php, I have the following code to generate JSON data: <?php $locations = array( array('2479 Murphy Court', "Minneapolis, MN 55402", "$36,000", 48.87, 2.29, "property-detail.html", ...

A guide on parsing a stringified HTML and connecting it to the DOM along with its attributes using Angular

Looking for a solution: "<div style="text-align: center;"><b style="color: rgb(0, 0, 0); font-family: "Open Sans", Arial, sans-serif; text-align: justify;">Lorem ipsum dolor sit amet, consectetur adipiscing e ...