Increase the identification of HTML element with jQuery

I've encountered an issue while trying to increment the id of 2 HTML elements, hwAddition and itemNumber, upon a button click event. The HTML code in question is as follows:

<div id="hwAddition">
    <div id="itemNumber" style="text-decoration: underline; font-size: large;">Item #</div>
    <div class="form-row">
        <div class="form-group col-md-4">
            <label for="hwDescription" style="text-decoration: underline;">Description</label>
            <form:textarea id="hwDescription" type="text"
                class="form-control short" path="hwDescription"
                name="hwDescription" placeholder="Description" maxlength="100"
                rows="2" style="resize: none;" />
        </div>
        <div class="form-group col-md-4">
            <label for="hwSerialNumber" style="text-decoration: underline;">Serial
                #</label>
            <form:input type="text" class="form-control" path="hwSerialNumber"
                name="hwSerialNumber" placeholder="Serial #" maxlength="100" />
        </div>
        <div class="form-group col-md-4">
            <label for="hwModelNumber" style="text-decoration: underline;">Model
                #</label>
            <form:input type="text" class="form-control" path="hwModelNumber"
                name="hwModelNumber" placeholder="Model #" maxlength="100" />
        </div>
    </div>
    <hr />
</div>

The jQuery script responsible for this functionality is provided below:

var count = 1;

$(function() {
    $("#hwAddition").attr('id', 'hwAddition' + count);
    $("#itemNumber").attr('id', 'itemNumber' + count);
});

$('#hwAdditionButton').click(
    function() {
        $("#itemNumber" + count).clone().attr('id', 'itemNumber' + (count+1));
        $("#hwAddition" + count).clone().attr('id', 'hwAddition' + (count+1))
                .insertAfter("#hwAddition" + count);            
        count++;
    });

However, I have observed that although the hwAddition ids are being incremented correctly, the itemNumber ids do not change as expected. This anomaly can be seen in the image link provided here, where after three clicks there are hwAddition1, hwAddition2, hwAddition3, but only itemNumber1, itemNumber1, itemNumber1. Any insights on why the itemNumber id isn't updating would be greatly appreciated.https://i.stack.imgur.com/ilHL8.png

Answer №1

Could you please make an adjustment to your script? You need to add code that increments the "ID" for itemNumber.

$('#hwAdditionButton').click(
    function() {                
        let clonedObject = $("#hwAddition" + count).clone().attr('id', 'hwAddition' + (count+1));
        clonedObject.find("#itemNumber" + count).attr('id', 'itemNumber' + (count+1));                
        clonedObject.insertAfter("#hwAddition" + count);
        
        count++;
    });

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 issues with incorporating a component into another component in VueJS

Having spent approximately 30 hours on diving into VueJS, I am encountering some difficulties when it comes to using a component within another component. Seeking assistance from someone knowledgeable in this area to provide me with some clarification. Pr ...

Having trouble with React MaterialUI <ListItemSecondaryAction> getting stuck while dragging within a react-beautiful-dnd Draggable?

I am currently utilizing react-beautiful-dnd to create draggable list items with the help of Material UI ListItems. Each of my ListItems consists of a ListItemText and a ListItemSecondaryAction which acts as a target for triggering a context menu (enclosi ...

Several features - Second function malfunctioning

The initial inquiry is effective. However, the subsequent one is encountering issues as it is failing to confirm if an email contains the "@" symbol. My attempted solution involved reordering the functions related to email validation. <body onload="ch ...

Displayed hours may not be complete on the Dhtmlx timeline

I'm experiencing an issue with the cell timeline feature in DHTMLX. I want to ensure that the cell size is consistent and displays the full hour, or horizontally scrolls if the hours extend beyond the device screen. Despite my efforts to consult the ...

NodeJS: Implement a method to delete a file or folder using a path without the file extension (Strategic approach)

I am facing a challenge in deleting a file or folder based on a path that does not include an extension. Consider the path below: /home/tom/windows The name windows could refer to either a folder named windows OR a file named windows.txt Given that the ...

Retrieve webpage using HTML stored in web storage

I am exploring a new idea for an application that utilizes local storage, and I am seeking guidance on the most effective way to load content after it has been stored. The basic concept of the app involves pre-fetching content, storing it locally, and the ...

Collaborate and apply coding principles across both Android and web platforms

Currently, I am developing a web version for my Android app. Within the app, there are numerous utility files such as a class that formats strings in a specific manner. I am wondering if there is a way to write this functionality once and use it on both ...

Change the websocket origin to localhost in a javascript setting

My server is hosting the domain example.com. Every time a user loads a page on this server, it utilizes a WebSocket client in JavaScript to connect to another WebSocket server. However, the other server has CORS enabled, which prevents the connection bec ...

"React - encountering issues with state being undefined when passing child state up through parent components

I am currently navigating the world of react and have encountered a hurdle. I find myself facing difficulties in updating the parent component based on changes in the child state. I was able to pass the child state to the parent by linking the child's ...

I am looking to continuously update the progress bar as the AJAX responses are being received

In order to update the progress bar with every response individually, I encountered an issue where multiple responses were being received at once and only the last one would update the progress bar. Despite trying async:false, the progress bar would only u ...

The challenge with linking within Layerslider

Having some trouble with an external link to a specific layerslider slide (html version, NOT wordpress). Here is the webpage in question: After reaching out in the support forum, I was advised to use this javascript: <a href="javascript:void(0);" onc ...

Maintaining the position of the screen as you type in information that is located outside of the container

I am encountering an issue with the input/text-area element in absolute position extending halfway outside the container. The screen position seems to follow the caret as I type, but I'd prefer to keep writing and have part of the text hidden beyond t ...

What is the best way to trigger a useReducer dispatch function from a different file that is not a React component, without relying on Redux?

In my project, I have a function component that shows a game board named "EnemyBoardComponent.tsx" const enemyBoardReducer = (state:number[][], action:Action)=>{ switch(action.type){ case "update": { return EnemyBoard.getGrid(); ...

When executing class methods, Ember.js encounters errors stating "method does not exist."

I am facing a situation where I need to trigger a model reload when a user clicks a refresh button. In the past, I successfully implemented this with Ember-Model. However, since migrating to Ember-Data, I am encountering an error when attempting to execute ...

Alerting old session data following an AJAX request

After making an AJAX call that updates a $_SESSION variable, my <script> is supposed to echo out the new variable. However, it keeps alerting the old data even though the data is reaching the .php page and being stored in the session. I've attem ...

AngularJS Uncaught ReferenceError: variable is not

I am facing an issue where I cannot retrieve a value from a function. I am performing REST requests for testing purposes and when trying to get a date, it always returns undefined. An Illustration $http.get('app/components/home/controller/test_calen ...

Unable to align the row in the center

I'm having trouble centering a row with 4 columns. It seems off when I look at the picture below, specifically at the vertical border under the "most read" blue square. html file: <div class="block-section"> <div class="sm-section-wrapper" ...

Tacking the progress bar onto an array of $.ajax() calls within a Promise.all

FINAL UPDATE 25/06/20: After a thorough investigation, I discovered the root causes of why the progress bar was not functioning as intended. Firstly, dealing with $.ajax() proved to be cumbersome due to its lack of proper promise handling. To resolve this ...

excess white space appears in the mobile version

I recently completed a website using both materializecss and bootstrap platforms. While I know this may not be the best practice, it worked for my needs. However, I am facing an issue with the mobile view. When I reduce the viewport size, a margin appear ...

AngularJS Constants in TypeScript using CommonJS modules

Let's talk about a scenario where I need to select a filter object to build. The filters are stored in an array: app.constant("filters", () => <IFilterList>[ (value, label) => <IFilterObject>{ value: value, label: label } ]); i ...