Increase or decrease the quantity of items by cloning with Jquery and dynamically changing the ID

Currently, I am working on a jQuery clone project where I need to dynamically add and delete rows. Despite searching extensively on Stack Overflow and Google, I only have a basic understanding of how jQuery clone works.

Any suggestions would be greatly appreciated.

Below is the jQuery code I am using:


var count=0;
$(document).on("click", ".phn_btn_more", function () { 
    var $clone = $('.cloned-row:eq(0)').clone();
    $clone.find('[id]').each(function(){this.id+='someotherpart'});
    $clone.attr('id', "added"+(++count));
    $('.cloned-row:eq(0)').after($clone);
});

$(document).on('click', ".btn_less1", function (){
    var len = $('.cloned-row').length;
    if(len > 1){
        $(this).closest(".btn_less1").parent().parent().parent().remove();
    }
}); 

Although I can now increment IDs dynamically with this updated code, it seems to be cloning two times instead of once.

When clicking the "add more" button, the div is being cloned but instead of one, I am getting two duplicated divs. Additionally, I am trying to increment ID and name dynamically.

I understand that this may be considered a possible duplicate issue, but I am still unsure why I am unable to increment the ID and name. Also, for the first div, the 'btn_less' class won't be available and should only appear after the user clicks 'add more' from the second instance onwards.

Below is the HTML code snippet:


 <div class="em_pho cloned-row" id="phone_content">
     <select id="sel_phntype" name="sel_phntype" class="sslt_Field">
         <option selected='selected' value="">Phone Type</option>
         <option value="BUSN">Business</option>
         <option value="CAMP">Campus</option>
         <option value="CELL">Cellphone</option>
         <option value="CEL2">Cellphone2</option>
         <option value="FAX">FAX</option>
         <option value="HOME">Home</option>
         <option value="OTR">Other</option>
     </select>
     <span class="ph-inline">
         <input type="text" class="cc_field" placeholder="Country Code" id="txt_CC" maxlength="3" name="txt_CC" /> 
         <input type="text" class="pn_field" placeholder="Phone Number" id="txt_Pno" name="txt_Pno" />
         <input type="radio" name="preferred" id="rad_Prf" value="preferred">
         <label class="radio-label">Preferred</label>
         <input type="button" class="phn_btn_more" id="buttonvalue"/>
     </span>
 </div>

Your assistance on this matter will be much appreciated.

Thanks & regards, Mahadevan

Answer №1

Unsure if this is exactly what you were looking for.

JSfiddle link

If I missed anything or made any errors, please let me know.

JQuery

var count=0;

    $(document).on("click", ".phn_btn_more", function () { 
        var $clone = $('.cloned-row:eq(0)').clone();
        //alert("Clone number" + clone);
         $clone.find('[id]').each(function(){this.id+='someotherpart'});
         $clone.find('.phn_btn_more').after("<input type='button' class='btn_less1' id='buttonless' value = 'remove'/>")
        $clone.attr('id', "added"+(++count));
        $(this).parents('.em_pho').after($clone);
    });

    $(document).on('click', ".btn_less1", function (){
        var len = $('.cloned-row').length;
        if(len>1){
            $(this).parents('.em_pho').remove();
        }
    }); 

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

Styling Material UI components with CSS is a great way to

I'm facing difficulties while working with Material UI components. Currently, I have a Material UI table and I want to center-align the text within it. The standard CSS of Material UI contains an element named MuiTableCell-root-60 which has a text-a ...

Master the art of returning two functions within a single function in Javascript with NodeJS and ExpressJS

Currently, I am facing an issue where I need to combine two objects and return them in one function. The challenge lies in the fact that both objects have almost identical properties, but different values. To tackle this problem, I created two separate fu ...

When I click on a specific div, another div should be appended to the main_div

I am just starting to learn about jquery and have a simple application where I need its functionality. Within my layout, there are several small divs on the left side (such as div1, div2...), and one main div in the center of the page. My goal is to have ...

My Express server is having trouble loading the Static JS

I'm feeling frustrated about this particular issue. The problem seems to be well-solved, and my code looks fine, but I can't figure out what's wrong . . . I have a JavaScript file connecting to my survey page, which I've added at the b ...

Tips for maximizing efficiency and minimizing the use of switch conditions in JavaScript when multiple function calls are needed

After coming up with this code a few minutes ago, I began to ponder if there was a more elegant way to optimize it and condense it into fewer lines. It would be even better if we could find a solution that eliminates the need for the switch condition altog ...

Displaying dynamic data in a Bootstrap modal using Laravel

I have implemented a bootstrap modal in my dashboard. The button that triggers the modal is placed on another page where I extend the dashboard layout. When I click on a button with a different product ID, I want the modal to display information related ...

Tips for automatically closing one sub menu while selecting another sub menu

I am working on a code snippet to manage the menu functionality. My goal is to ensure that when I click to open one submenu, any other currently open submenus should automatically close. ;(function($) { // Ensuring everything is loaded properly $ ...

Tips for displaying information from two separate MongoDB documents on a single webpage with the help of Mongoose and Express

Currently, I am working with NodeJS, Express, EJS, and Mongoose. While I have a good grasp on most of these technologies, I find myself navigating through the complexities of Mongoose. In my project, I have established two Models that are interconnected w ...

Struggling to fetch a custom attribute from the HTML Option element, receiving [object Object] as the result instead

I've been facing a challenging issue all day. My task involves making an ajax call to a predefined JSON file and trying to save certain contents into option tags using custom attributes. However, every time I attempt to retrieve the data stored in the ...

Issue with React and JavaScript: Object is displayed on the console briefly before disappearing

I am having an issue with my sign up page where the console log of the two fields disappears after a second. I would appreciate any assistance on this matter. Below is the code for the sign-up form: export default function SignUp() { const [firstNam ...

Combining CSS to Align Two Form Fields Side by Side

I recently came across an online form and I'm attempting to customize it by aligning the phone and email text fields next to each other. I have made some progress, but the formatting is not quite right. The fields are too small and adjusting their siz ...

The state of my React components keeps disappearing

Within my code, I have implemented a click event on the InterestBox to trigger updates in its appearance and alter the state of its parent container. However, despite inspecting the element using React Developer Tools and attempting API requests, the stat ...

Modify the appearance of material-ui checkbox

For my project, I am utilizing React along with the styled-component package for styling. However, I am facing an issue when it comes to styling the Material-ui checkbox using styled-component. The problem lies in narrowing the border of the checkbox, as t ...

Adding items to a jCarousel using C# programming language is a simple process that involves following

I am struggling to display images in jcarousel using a C# Webmethod and jQuery Ajax. Here is my setup: My HTML structure: <div> <ul id="mycarousel" class="jcarousel-skin-tango" style="float: left"> </ul> </div ...

The d3 drag functionality is only active when the axis ticks are selected

Currently, I am developing a unique package that combines Angular and D3 (v3) and my main focus is on integrating D3's dragging feature into the package. Although I am very close to achieving success, there is a minor bug that I need to address. When ...

The width property is not being passed down to the table

I'm experiencing difficulties with the scaling of my body content. When the page is initially opened, it scales to 100%. However, when I resize the screen to make it wider, the content gets bigger but when I try to make it smaller again, it remains a ...

Redirecting in Next.js from an API route

I am in the process of developing a backend application that necessitates user authentication. Within this project, I'm utilizing 2 external APIs: API A: responsible for managing user accounts and sessions API B: utilized for executing CRUD operation ...

Navigating to a new webpage element within a div class using Selenium

Struggling with selecting an element on a webpage using Selenium? Despite my experience with this website and methods like css selector and XPath, I can't seem to pinpoint the element in a troublesome section. The challenge arises when I attempt to in ...

What steps can I take to make sure a particular node is successfully loaded and ready for use using JavaScript/jQuery?

When making a reservation at a hotel using the CJS Chrome extension, I am attempting to extract information about available rooms and rates both when the page loads and when the user changes dates. My current method involves injecting JavaScript into the p ...

Is it achievable to create shadows that do not overlap?

When you hover your mouse over the pill-shaped object, it should smoothly move over the circle as desired. However, the shadow of the circle still remains visible creating an unwanted effect. I am looking for a solution where the shadows do not overlap but ...