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

Utilize a single submit button to navigate through multiple pages dynamically using JavaScript

I would like to navigate to different rooms with just one button using JavaScript. For instance, there are three rooms: "Kitchen, Toilet, and Bedroom". How can I utilize JS to enter any of these rooms based on my selection? If I input "kitchen" in the text ...

Updating the state on a click event triggered by a MenuItem in React using Material UI

I'm currently working on implementing state changes based on dropdown selections using Material UI. However, I've encountered an issue where the code snippet below (simplified) only returns the list item, and I'm unsure what steps to take n ...

Align the content evenly on several cards using Material-UI

Trying to work on some frontend coding, but struggling with getting the content justified properly in fixed-height MUI cards. Each card consists of a title, description, divider, and author, but I can't seem to get everything aligned correctly within ...

Top method for dynamically refreshing an HTML table

Information Background In a presentation site, there is an HTML table displaying data from a Postgres database. The first row of the table needs to be highlighted and the data should be ordered by the "Votes" column in descending order. Although the backe ...

The challenge of margin collapse

I am currently working on resolving a margin collapse issue. I am puzzled by the overlapping paragraphs and I really need to understand why this problem is happening. I suspect it may be a collapsing margin issue. Please take a look below: https://i.sta ...

Determine the number of JavaScript functions present on a webpage using JavaScript

Hey there! I'm interested in counting the javascript functions on a specific page and then sending this count via ajax. Do you think it's possible to do this using javascript? What would be the best approach? Thanks in advance! Just to explain f ...

Unable to use jQuery to send a basic ajax request in order to retrieve a json file

Here is the code snippet: $(function() { $.ajax({ url:'http://localhost:3000/business_places', type:'GET', dataType:'jsonp', done: function(data){ alert(1) }, error: function(data) { ...

Step-by-step guide to inserting an image into a Table Cell

I want to include my PDF image at the conclusion of the text in my table cell When it comes to my Table, I'm hoping that the image can be combined with the text seamlessly after it finishes <TableCell component="th" scope="row" className = {class ...

What is the best way to automatically log out a user when a different user logs in on the same browser?

Currently, I am encountering an issue where there are two separate dashboards for different types of users - one for admin and the other for a merchant. The problem arises when an admin logs in on one tab and then a merchant logs in on another tab in the s ...

Top method for displaying loading popup using $http

As a newcomer to Angular, I am curious to know if it's possible to achieve the following scenario and also where I can find documentation to help me get started. The scenario: In my MEAN app, there is currently a 'loading...' popup controll ...

The ng-show and ng-hide directives are not working as expected, and there are no error

I'm currently working on a Todo App using AngularJS 1.x (version 1.6), but I'm having issues with ng-show and ng-hide functionality. The aim is to have a text box appear in the todo section when the edit button is clicked to modify existing todos ...

Building a row of five dynamic columns using Bootstrap's responsive design

I'm looking to set up a row with 5 responsive columns that have equal padding on all sides, but I'm struggling to find the best way to do this using Bootstrap. Here's my current HTML: <div class="row five-col-row"> < ...

Tips for modifying the function of an Electron application using an external JavaScript file

This is the project structure I envision. https://i.stack.imgur.com/ocRp9.jpg kareljs folder houses an Electron app, and upon running npm start within that directory, a window appears and executes the run method of karel.js when the button Run Karel is ...

Inject JSON data into a JavaScript array

I am dealing with a JSON file in the following format: [{"excursionDay":"2"},{"excursionDay":"3"},{"excursionDay":"4"}] My goal is to extract the values of excursionDay and store them in an array in JavaScript like this: dayValues = [2,3,4] Here is m ...

Sinon's fakeTimers failing to trigger

I'm encountering an issue with sinon's fakeTimers while working in a setup that includes Marionette.js, underscore, and chai test runner. Strangely, when I place a breakpoint in Chrome and step through the code, my timer functions as expected. Ho ...

Darken the entire webpage and gradually fade in a specific div element using Jquery

Currently, I am working on implementing the following functionality: - When a link is clicked, it should trigger a function to show a DIV (#page-cover) that will dim down the entire background. This div has a z-index of 999. - Following the dimming effect, ...

Making sure that a commitment does not come to fruition

Perhaps this code snippet below functions correctly as it is, but I'm uncertain if it's the best approach to prevent potential runtime issues. Here's the code in question: const ep = `${environment.api.baseUrl}/login`; return this.http.pos ...

Look for specific content within a div tag and display that div at the top of the page

<div class="search-container"> <input type="text" class="input-medium search-query" placeholder="Search"> <button type="button" class="btn">Search</button> </div> <div class="panel panel-default"> ...

Error Handling for Ajax Functions Not Triggering

I have a function that works perfectly when there are results to display. However, I want a message to show up for "No Results" if there are no program host records to display. But currently, nothing happens in that case. Any suggestions? Thank you for you ...

Displaying a Dynamic Loading Animation While Making an AJAX Call with jQuery

When a user clicks on the active status button, it should switch to inactive with a red color, and vice versa. Currently, I can update my status in the backend, but I have to refresh the page to see the changes every time! My requirement is that during t ...