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

Exploring the Process of Printing Python Dictionaries

There is a Python dictionary named top_words. To print its contents, I have used the following code snippet. for word, count in top_words.items(): print(word, count) This displays something like shown in the image at this link. I am trying to figu ...

Glassfish could not locate the MessageBodyWriter for the specified media type of Application/json

After successfully implementing my first method using JAX-RS to create simple restful JSON, I encountered an issue when adding a second method to retrieve all "vendorNOS" ID. Upon viewing the browser, I received an exception despite debugging the Restful s ...

Vue.js numerical input module

My approach involves utilizing Numeral.js: Vue.filter('formatNumber', function (value) { return numeral(value).format('0,0.[000]') }) Vue.component('input-number', { templa ...

Updating multiple documents in Mongoose that have a specific element in an array

I have structured a Mongoose schema like this: const mongoose = require('mongoose'); const ItemSchema = mongoose.Schema({ id: { type: String, required: true, }, items: { type: Array, required: true, }, date: { type: ...

Ways to disable the ability to close a bootstrap modal by pressing the backspace key

How can I enable the backspace button in a Bootstrap Modal form for textboxes and textareas? $('body').keydown(function (e) { if ($('#myModal').is(':visible')) { if (e.keyCode == 8) { retu ...

Showing or hiding child content based on the selected state of a radio button

This is a follow-up question from a previous one on changing check boxes to radio buttons. Now, I need to display child radio buttons and change the background color when the parent radio button is active. The child radio buttons should be hidden and the b ...

A dynamic Java web framework that combines RESTful JSON services with the power of HTML5 and jQuery AJAX functionality

As we approach the year 2013, the era of HTML5, jQuery has solidified itself as the go-to standard for web Javascript development. Back in 2010, this link was quite popular: I am searching for a Java web framework that can expose domain classes through R ...

Modifying the selected color of DropDownMenu List items

Hey there! I'm currently trying to modify the color of a material-ui element that is selected, but I'm having trouble finding any resources on how to accomplish this. My goal is to switch this pinkish shade to a more soothing blue hue. Update: I ...

Effortlessly explore Washington D.C. with a single click using advanced search filters

On my devices/index page, I have a requirement to only display "out of order" devices when a specific checkbox is flagged. To achieve this, I implemented the CakeDC search plugin 3 and utilized the DevicesTable model as follows: public $filterArgs = [ ...

Steps for creating a TypeScript project for exporting purposes

Forgive me for my lack of experience in the js ecosystem. Transitioning from static languages to typescript has been a positive change, though I still find myself struggling to grasp the packaging/module system, especially when coupled with typescript defi ...

Creating a dynamic form where input fields and their values update based on user input in jQuery

In my form, I have an input field where users will enter an ISBN number. Based on the input number, I need to populate two other input fields: one for book title and one for author name. I am currently calling a JavaScript function on the onblur event of ...

Ways to analyze three PHP arrays and organize outcomes that are not duplicated into separate new arrays

I have an array containing three nested arrays. $rubros array(3) { [1]=> array(8) { [0]=> array(1) { ["idRubro"]=> string(1) "1" } [1]=> array(1) { ["idRubro"]=> str ...

Guide on automatically removing a DOM element in Jquery after a set amount of time

Is there a way to delete an HTML element after a specific period of time? If a certain condition is met before the allotted time, I want to pause the timer from deleting the element. Here's a snippet of code for reference: <ul> <li dat ...

The fragment shader must not declare any varyings with the same name but different type, or statically used varyings without being declared in the vertex shader. An example of this is

I'm struggling with shaders because I want the fog to be reflected in the water using Three.js sky_sun_shader. I added the following code snippet to the fragment Shader: THREE.ShaderChunk[ "fog_pars_fragment" ], THREE.ShaderChunk ["fog_fragment" ], ...

Information is only displayed within the Node Request function and is not accessible to

I am currently developing a small web scraping tool using Node (Express) to search URLs from a list. However, I'm encountering an issue with accessing the results of the search outside of the request callback function in a forEach loop. Can anyone hel ...

Tips for concealing a Donut Chart when the value is zero and displaying the chart in grey when there is an empty value using

I've recently switched from using ChartJs to EchartsJS in my project, but I'm facing a specific challenge. When all items in the chart have a value of 0, EchartJs still displays all colors equally. However, I want the chart to be hidden in such ...

What are the steps to decode a JSON response using jQuery?

Working on a fun little web app for my significant other and me to keep track of movies we want to watch together. I'm exploring using TheMovieDatabase.org's API (which only supports JSON) to simplify the process of adding movies to our list. The ...

Issues with displaying images in Fancybox

I've integrated FancyBox into my website, but I'm experiencing a minor issue. While the FancyBox works perfectly in Dreamweaver, it seems to malfunction in various browsers. As someone who is not well-versed in programming, I'm struggling t ...

AngularJS: when ng-route clashes with Bootstrap datetimepicker

I have nearly completed my calendar app and I am looking to integrate the datetimepicker for updating events. You can find the datetimepicker that I am using at this link: Below is an example of how I have utilized it in HTML: <div class="dropdown" s ...

Injection of Angular state resolve into controller fails to occur

I'm attempting to ensure that the value from ui-router's resolve is successfully passed to the controller portalsForUserCtrl. Take a look at the router code below: (function () { 'use strict'; var myApp = angular.module("myApp", ["co ...