Using jQuery to dynamically insert a table row with JSON data into dropdown menus

I'm working on a web form that includes a table where users can add rows. The first row of the table has dependent dropdowns populated with JSON data from an external file. Check out the code snippet below:

// Function to add a new row
$(function(){
    var newgroup = $('<tr>').addClass('rec-rows');
    $('#addRow').click(function(e){
        e.preventDefault();
        $('.rec-rows').first().clone().appendTo(newgroup).appendTo('#details');     
    }); 
});

// onChange function for dropdown selection
$(".rec-rows #section").live('change',function(){
    var sSec = $(this).parent().find('#section').val();  

    $("#divParts").hide();
    $("#divDesc").hide(); 
    $("#divGroup").hide(); 

    if(sSec=="select") {
        $("#divCategory").hide();
    } else {
        $.getJSON("static/site_category.json",  function(json) {
            var catJson = json[sSec];
            var options = "<option value=\"select\">Select Area Type</option>";
            for(i=0; i<catJson.length; i++) {
                options += "<option value=\"" + catJson[i].ky + "\">" + catJson[i].val + "</option>"
            }
        });
    }

Although theoretically, each added row should work independently with the onChange code, in reality, the values are getting updated on the first row instead of the specific one. Here is the initial setup of the table:

<td width="" align="left"> 
<div>
<select id="section" name="section" style="margin-top:15px;"> 
<option value="select">Select Area</option> 
<option value="a">a</option> 
<option value="b">b</option> 
<option value="c">c</option> 
</select> 
</div> 
</td> 

I would appreciate any guidance or support to fix this issue and have the code function as intended - allowing for independent dropdown updates on each row. Thank you for your help.

Answer №1

Check out my solution for dynamically adding a row to the beginning of a table:

How can I dynamically generate a table row with its tds?

This could be useful in your case.

Also, I noticed a potential issue.

Update $("#section").change(

to:

$("#section").live('change',...

This might be the reason why the new dropdowns are not functioning properly.

Answer №2

Success! I received guidance to clarify the parent as shown in the following example:

$(".section").change( function () {
var sSec =$(this).val();  
context = $(this).parents("tr");
if(sSec=="select") {
$("#divCategory", context).hide();
} else {
$.getJSON("static/site_category.json",  function(json) {
var catJson = json[sSec];
var options = "<option value=\"select\">Select Area Type</option>";
for(i=0;i<catJson.length;i++) {
options +="<option value=\""+catJson[i].ky+"\">"+catJson[i].val+"</option>"

Now, when adding a new row, a row is added and the dropdowns are updated based on user selection for that specific row.

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

Having difficulty showcasing API call results in a Vue.js component

I am currently experimenting with Vue.js in an attempt to showcase results from a Wikipedia API call within a component using the v-for directive. However, I seem to be encountering some backend issues that I cannot pinpoint. To access the jsFiddle link, ...

How can one ensure that Discord waits for a script to complete running, and how can you prevent Discord from responding until all necessary data has been obtained?

I recently started working with node.js and asynchronous programming, and I'm facing a challenge that has me puzzled. My goal is to create a Discord bot that fetches data from a third-party website. While I can successfully retrieve the data and see i ...

Here is a unique version: "In Javascript, users can trigger the function this.Something() from within this.img.onload by

I have some code that looks like this... Thing function () { var img = new Image; DoSomeStuff function() { //Code here that relies on my image being loaded... }; InitMe function(src) { this.img.onLoad = this.DoSomeStuff; ...

Strategies for retaining additional fields added via JavaScript when the page is refreshed

var newField = document.createElement("lastExp"); newField.innerHTML = 'insert new form field HTML code here'; document.getElementById("lastExp").appendChild(newField); I have a button that adds an additional form field with a simple click. ...

Accessing store in Vue, the getter function returns a value representing whether the user is currently logged

I have the user state stored in my Vue store, but when I try to access it like this: let isLoggedIn = store.getters.isLoggedIn Instead of getting a simple true or false, I see this in the console: ƒ isLoggedIn (state) { return state.user ? true : false ...

What is the best way to link a variable to a specific property within a

I am facing an issue with adding data from the server to a JSON property and displaying it. I know that JSON only accepts primitive types, so how can I dynamically add data to a JSON property? For instance, in the code snippet below, I am trying to assign ...

Creating a route-guard in a Vue.js/Firebase authentication system for secure navigation

I have created a Vue.js/Firebase authentication interface following a tutorial. The app is mostly functioning properly, but I am experiencing issues with the route guard. Upon signing in and redirecting from "http://localhost:8080/home" to "http://localh ...

What is the process for adding parameters to a Fetch GET request?

I have developed a basic Flask jsonify function that returns a JSON Object, although I am not certain if it qualifies as an API. @app.route('/searchData/<int:id>',methods=["GET"]) def searchData(id): return jsonify(searchData(id)) Curr ...

Employing DOM manipulation within Vue unit tests as a last resort

What steps should I take to update my unit test in order to accurately validate the following scenario? Method: close(event) { const element = !!event?.target?.closest('#target') if (!element) { this.isVisible = false } }, Jest test: ...

Is NextJS rendering solely on the server, or is it capable of rendering on both

Within my users.js JSX file, I have an exported component that looks like this: ... return <MainContainer keywords="users"> export default Users During the process of SSR/SSG, the browser displays the users HTML (comprising of <li> t ...

Working with AngularJS: Accessing a JSON file from the local directory

The answers to my previous questions on this topic have not been satisfactory. It seems that most examples and tutorials for AngularJS online always define tiny JSON arrays directly inside the JavaScript code... So, let's simplify things with a basi ...

How to convert an array of keys and an array of values into an array of objects using JavaScript

My question is similar to the one found here: Merging keys array and values array into an object using JavaScript However, I am unable to find a solution for my specific scenario. If I have these two arrays: const keys = ['x', 'y', &ap ...

The typical initial default argument to be passed to the function using fn.apply

Recently, I discovered the power of using fn.apply() in JavaScript to store function calls with all their arguments intact for future use. In my specific situation, I don't require the first argument, which is the context (this), and I want to find a ...

Looking for assistance with a Vue.js BMI Calculator project

Currently, I am delving into Web Development using Vue. As part of my project, I have constructed a component that calculates the BMI (Body Mass Index) of an individual. To collect the necessary data, I have implemented a form utilizing bootstrap-vue. Howe ...

Testing actual HTTP requests in unit and integration tests with AngularJS

Attempting a request that was not mocked using $httpBackend.when in an Angular 1.x unit/integration test will lead to an error: Error: Unexpected request: GET /real-request Is there a way to perform actual HTTP requests with ngMock and the Karma+Jasmin ...

issues with jasmine angularjs tests exhibiting erratic outcomes

During the execution of my unit tests, I often encounter a scenario where some random test(s) fail for a specific controller without any apparent reason. The error messages typically look like this: Expected spy exec to have been called with [ Object({}) ...

Utilizing getStaticProps for Performance Optimization in Next.js

I am currently in the process of setting up a blog using Next.js and GraphCMS. I have an ArticleList component that I want to display on multiple pages, such as my homepage and under each article as a recommendation. Since the article list is sourced from ...

An issue arises when ng-pattern fails to recognize a regular expression

My form includes inline validation for a specific input field. <form name="coForm" novalidate> <div> <label>Transaction: </label> <input type="text" name="transaction" class="form-control" placeholder="<Dir ...

Exploring the integration of methods in Vue.js components

Within my Vuejs project, I developed a new form component and integrated it into the main index component. This new component needs to validate certain fields, with validation methods already created in the parent component. However, I am facing difficulti ...

The POST request to the localhost API endpoint resulted in a 404 Not Found error

Whenever I try to send a POST request to "/api/auth/signup" in my JavaScript application, I keep getting a 404 Not Found error. My goal is to create a MERN application for a Modern Real Estate Marketplace. This is the code snippet causing the is ...