Learn how to dynamically assign a new ID and name to a cloned div element using jQuery based on the original element's ID

Within a DIV, there are two Input Textboxes present.

I am attempting to duplicate the above div, meaning I want two additional textboxes cloned from the original ones.

However, I am encountering challenges when it comes to assigning new IDs and Names to the clonable input textboxes.

<div class="panel" id="MyJuicePanel">
<div class="cloning" id="MyJuicePanel1">
<input type="text" value="" name="juice.apple.poland[0].varietyName" id="juice.apple.poland0.varietyName">
<input type="text" value="" name="juice.apple.sweden[0].varietyName" id="juice.apple.sweden0.varietyName">    

When creating a new div, I aim to replace the aforementioned IDs from 0 to 1, 2, 3...n

newElem.find("#"+InputId).attr('name', InputName_New).val('');     

An alternative method, which I do not prefer: If I utilize a Class in the input like class="input1", then it becomes easier to assign new IDs. However, I am hesitant to use classes and would rather find elements based on their IDs, change the name to a new one, and subsequently alter the ID based on the new name.

For further clarification, please refer to this fiddle: https://jsfiddle.net/vc6zappq/

Answer №1

Utilizing data-id and data-type for efficient coding

            var IdValue = $(this).attr('data-id')+1;
            var TypeValue = $(this).attr('data-type');
            var NewName = "juice.apple."+TypeValue+"["+IdValue+"].varietyName";
<div class="panel" id="MyJuicePanel">
        <div class="cloning" id="MyJuicePanel1">
            <input type="text" data-id="1" data-type="poland"  value="" name="juice.apple.poland[0].varietyName" id="juice.apple.poland0.varietyName">
            <input type="text" data-id="1" data-type="sweden" value="" name="juice.apple.sweden[0].varietyName" id="juice.apple.sweden0.varietyName">
        </div>
                  <button id="addBut" type="button" >Add It</button>
    </div>

Answer №2

One issue lies in the loop through the old inputs, allowing access to change their attributes before looping through the new ones.

$(cloneId+" input").each(function(){

Should be updated to

newElem.find("input").each(function(){

Then, modifications to the inputs' attributes can be made as follows:

$(this).attr("id", InputId_New);
$(this).attr("name", InputName_New);

https://jsfiddle.net/vc6zappq/8/

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

Is there a way to adjust the placement of the h1 tag using the before pseudo-element?

I'm looking to place an image on the left side of each h1 tag. I've been attempting to utilize the before pseudo element for this task. The issue arises when there is no content, causing the before pseudo element to overlap with the h1 tag. How ...

Whenever the cursor hovers over, the DIV above the iframe flickers

I'm having trouble placing a social button on top of an iframe that contains a YouTube or Vimeo video. The social buttons are located within a div container, which reveals or hides the content with JavaScript. However, I'm experiencing a blinking ...

Trouble arises when attempting to compare two JSON files with an undefined issue

data-info.json {"price-comparison":[[{"Price":"0.0"},{"Code":"C0358102"}],[{"Price":"2.0"},{"Code":"C0876548"}]],"isEmployeeOJ":"Y"} script.js var dataInfo = $http.get("data/data-info.json").then(function (response) { $scope.dataInfo = response.data; ...

Is it possible to use bootstrap to hide specific components depending on the size of the media screen?

Struggling with styling responsiveness and hoping to find a Bootstrap class that can easily hide components on medium and small screens. I'm looking for a way to hide headings, paragraphs, buttons, and more without any extra hassle. ...

The correlation between frames per second (FPS) and the milliseconds required to render a frame in the stats plugin is known as the frame

Recently, I've implemented the Stats.js plugin to keep track of my three.js performance. Something seems off with the FPS (frames rendered per second) and MS (milliseconds needed to render a frame) information: According to my calculations, if it ta ...

Tips for eliminating choices upon button press

How do I remove nested options inside a select element upon button click? I'm not sure where my mistake is, could it be in the for loop? var select = document.getElementById('colorSelect'); var options = document.getElementsByTagName(&ap ...

What might be causing AngularJS to fail to display values when using TypeScript?

I have designed the layout for my introduction page in a file called introduction.html. <div ng-controller="IntroductionCtrl"> <h1>{{hello}}</h1> <h2>{{title}}</h2> </div> The controller responsible for handling th ...

Oops! Looks like we ran into a bit of a snag with the process_metrics

During our recent Protractor tests, we have been encountering warnings in the console: [12252:14584:1207/223118.187:ERROR:process_metrics.cc(105)] NOT IMPLEMENTED [12252:14584:1207/223118.187:ERROR:process_metrics.cc(105)] NOT IMPLEMENTED [12252:14584:120 ...

Dividing a select option

Looking to transform a single select element into multiple select elements using the separator "/" Here is an example of the original code: <select> <option value="1234">Type 1 / Black</option> <option value="5678">Type 2 / White& ...

Creating a unique card component with React and custom Tailwind CSS styling

I am working on creating a project component using React: Despite my efforts, I have not been able to find the correct documentation for assistance. Additionally, I am facing challenges in utilizing next/image to ensure that it is the correct size. This ...

Which file extension is superior for SEO: .html, .php, or .aspx?

Which file extension is more SEO-friendly: .html, .php, or .aspx? Or is an extension-less URL the best option for SEO? ...

The jQuery resize() method seems to be malfunctioning

My jQuery resize function is not working properly. I am trying to implement a custom scroll for devices with a width of 767, but it doesn't seem to be functioning as expected. Normally, the scroll works on devices above 767 in width. How can I fix thi ...

What is the best way to save a string for future use in Angular after receiving it from a POST request API?

I have been assigned to a project involving javascript/typescript/angular, even though I have limited experience with these technologies. As a result, please bear with me as I may lack some knowledge in this area. In the scenario where a user logs in, ther ...

jQuery doesn't seem to function properly upon initial click

Working with Rails and attempting to implement an ajax bookmark icon functionality. When clicking for the first time, the request is sent but the image does not change; however, subsequent clicks work as expected (request sent and image changes). This is ...

Rebuilding Javascript Files in Your Project with Laravel 9

I recently set up a Laravel 9 project on my Mac and am looking to incorporate Vue components. The default Laravel installation includes a Vue component (js/Components/ExampleComponenets.vue) which I successfully displayed in a view file. Wanting to custom ...

What is the syntax for implementing a for loop/for each loop in EJS?

I'm trying to figure out how to include this code snippet inside <% %>. I'm not sure if it's similar to a typical forEach/for loop. The documentation on EJS site is quite limited, so I've turned to this forum for help. <% incl ...

Configuring Node.js and express.js for my personal website to showcase my projects

I am new to node.js and I'm excited to implement it on my personal website as a way to start learning. I have successfully set up the node server, but I am struggling with setting up routing using express.js. All my files are typical static files like ...

Prevent elements from displaying until Masonry has been properly set up

My goal is to merge Masonry elements with existing ones. Currently, the items appear before Masonry initializes then quickly adjust into position a moment later. I want them to remain hidden until they are in their proper place. This is the snippet (with ...

Problem with Jsdom retrieving document

I am struggling to utilize jsdom for loading a local HTML file. Here is the code snippet: var config = { file: "filename", scripts: ["node_modules/jquery/dist/jquery.min.js"], done: function(err, window){ con ...

Node.js: The choice between returning the original Promise or creating a new Promise instance

Currently, I am in the process of refactoring a codebase that heavily relies on Promises. One approach I am considering is replacing the new Promise declaration with simply returning the initial Promise instead. However, I want to ensure that I am correctl ...