TransWikia.com

Increment HTML element ID using jQuery

Stack Overflow Asked by CDA the Programmer on December 18, 2021

I’m trying to increment the id of 2 HTML elements on a button click, hwAddition and itemNumber. You can see the HTML below:

<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 that I’ve written in order to do this is shown 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++;
    });

My issue is that for some reason, the hwAddition ids are incrementing correctly, but the itemNumber ids are not. You can see this in the image below where, after 3 clicks there is hwAddition1, hwAddition2, hwAddition3, but only itemNumber1, itemNumber1, itemNumber1. Any insight as to why itemNumber id isn’t incrementing would be appreciated.inspect

One Answer

Can you update your code? You must miss out the code to increase "ID" for itemNumber.

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

Answered by Liki Crus on December 18, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP