Tips for dynamically updating the id value while iterating through a class

Here's the HTML snippet I am working with:

<div class="info">
    <div class="form-group">
        <label class="control-label col-sm-2">Title</label>
            <div class="col-xs-10 col-sm-8">
                <input id="titleInfo" class="form-control" type="text" placeholder="Title">
            </div>
        <div class="col-xs-1 col-sm-1">
            <button class="btn btn-default remove_field"><i class="fa fa-remove"></i></button>
        </div>
    </div>
    <div class="form-group">
        <label class="control-label col-sm-2">Text</label>
        <div class="col-xs-10 col-sm-8">
            <textarea id="textInfo" class="form-control" type="text" placeholder="..."></textarea>
        </div>
    </div>
</div>

In my JSP file, there are several instances of the above code:

<div class="info">
    ...
</div>
<div class="info">
    ...
</div>
<div class="info">
    ...
</div>

What I want to do is change the IDs (titleInfo and textInfo) of each div with the class info in ascending order.

<div class="info">
    ..<input id="titleInfo1"..
    ..<textarea id="textInfo1"..
</div>
<div class="info">
    ..<input id="titleInfo2"..
    ..<textarea id="textInfo2"..
</div>
<div class="info">
    ..<input id="titleInfo3"..
    ..<textarea id="textInfo3"..
</div>

This needs to be done for all instances.

I plan to iterate through by the class info:

var x = 1;
$(".info").each(function() {
    //Now, I need to figure out how to update the IDs
    x++;       
});

Answer №1

To implement the necessary changes, please revise the code as shown below:

var x = 1;
$(".info").each(function() {
    var elems = $(this).find(".form-control"); // locate all input elements with the form-control class
    elems.each(function() { // traverse through the elements
         $(this).attr("id", $(this).attr("id") + x); // update the id attribute
    }); 
    x++;       
});

Modification

var x = 1;
    $(".info").each(function() {
        var elems = $(this).find(".form-control"); // retrieve all input elements with the form-control class
        $(elems[0]).attr("id", "titleInfo" + x);
        $(elems[1]).attr("id", "textInfo" + x);
        x++;       
    });

Answer №2

It's highly recommended to handle this server-side, specifically within the loop control responsible for generating those blocks. Nevertheless, here is a solution for your reference.

$("#infoBlock").each(function(i) {

    var $title = $(this).find("#titleInfo");
    var $text = $(this).find("#textInfo");
    $title[0].id += (i+1);
    $text[0].id += (i+1);
});

Feel free to check out this demo link as well.

Answer №3

Check out the following code snippet.

var x = 1;
$(".info").each(function() {
 var ele=$(this).find('.form-control');
  ele.each(function(){
     setIdentifier($(this),x)
   })
    x++;       
});

function setIdentifier(element,x){
  element.attr('id',element.attr('id')+x)
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<div class="info">
    <div class="form-group">
        <label class="control-label col-sm-2">Title</label>
            <div class="col-xs-10 col-sm-8">
                <input id="titleInfo" class="form-control" type="text" placeholder="Title">
            </div>
        <div class="col-xs-1 col-sm-1">
            <button class="btn btn-default remove_field"><i class="fa fa-remove"></i></button>
        </div>
    </div>
    <div class="form-group">
        <label class="control-label col-sm-2">Text</label>
        <div class="col-xs-10 col-sm-8">
            <textarea id="textInfo" class="form-control" type="text" placeholder="..."></textarea>
        </div>
    </div>
</div>

This portion of code accomplishes the same result.

Script

var x = 1;
$(".info").each(function() {
 var ele=$(this).find('.form-control');
  ele.each(function(){
      $(this).attr('id',$(this).attr('id')+x)
   })
    x++;       
});

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

Ways to retrieve the CSS class names associated with an element

To determine if an element has been selected, I rely on checking for the presence of an additional CSS class called "selected" that is added to the element The structure of my element is as follows: <div class="b-wide-option" data-bind="css: { selecte ...

Encountering module error 'internal/fs' after updating to Node 7

We have encountered some challenges after attempting to update our build server to node v7.0.0. Specifically, the application build task fails at the "bower_concat" step with the following error message: Loading "bower-concat.js" tasks...ERROR Error: Cann ...

How can we ensure the discord client object is easily accessible within event files?

I'm a beginner with Discord.js and I've been trying to figure out how to allow event and command files to access the main client instance. I want to be able to call client.database in an event file for CRUD operations, but I'm confused on ho ...

Using Ajax in a separate JavaScript file

How can I retrieve data from an Ajax call made from a different .js file? Here is the code snippet I have been working with: function ajax(url, success, error) { success += "(data)"; error += "(xhr, ajaxOptions, thrownError)"; console.log("St ...

What is the best way to place a div within another div?

I am facing a challenge where I need to insert a new div within another div before all its existing contents. The issue is that the outer divs do not have unique IDs, only classes as selectors. Unfortunately, I do not have control over the generation of th ...

Tips on displaying hyperlinks within a text area in an Angular application

In my Angular application, I am facing an issue with displaying hyperlinks within a text area box for dynamic content. The hyperlinks are not recognized and therefore cannot be clicked. Can someone please advise on how to properly display hyperlinks with ...

Executing a function following the removal of an element

I am trying to remove an element after exiting a jQuery dialog. I have used the .remove() function, but the element is not accessible after executing .remove(). How can I "destroy" an object in JavaScript and allow it to be called again without refreshing ...

"Bootstrap Carousel veers off from center alignment and aligns to the left instead

I found some code on a different website to put together a Bootstrap 5 carousel. Unfortunately, the alignment of my carousel is off as it is positioned to the left and I would prefer for it to be centered within the container. <div class="container ...

Guide on updating a specific item in a JSON array using npm request

I am currently working on setting a value in a JSON array utilizing a PUT request with the request module, specifically targeting one of multiple main objects within the array. The structure is as follows: [ 0: { status: 'pending' ...

Steps for ensuring a promise is fulfilled in Node.js and Firebase

I've been struggling with this issue for quite some time now and can't seem to figure it out. g_globalList.once("value").then(function(tickList){ var multiPaths = []; tickList.forEach(function(ticker){ ticker.val().forEach(fu ...

retrieve the path of any module within an npm monorepo

I am working on a project using an NPM monorepo structure which utilizes ECMAScript Modules (ESM): <root> |_package.json |_node_modules/ | |_luxon (1.28.0) |_packages/ |_pack1 | |_node_modules/ | | |_luxon (3.0.1) | |_main.js |_pack2 |_ ...

Error in Access-Control-Allow-Origin when using Node.js and JSONP

It seems like JSONP eliminates cross domain restrictions. I am currently attempting to create a JSONP service with node and express. Below is a simple example of the code: self.routes['/portfolio'] = function(req, res) { // Website you wis ...

What could be causing the fluctuation in ui-grid height as I scroll horizontally?

After using ui-grid in numerous projects without any issues, I recently encountered a strange issue when working with a large number of columns. With approximately 50 columns, as I scroll from left to right in order to view the columns that are off-screen ...

Switching over from an external style sheet to inline elements can be tricky, especially when it comes to integrating "dropdown" styles properly

I successfully created a stylish menu using a specific style sheet, but now I'm facing issues when trying to incorporate this menu into web pages with different style requirements. Realizing that loading the style sheet onto these new pages wreaks hav ...

Revamp the Bootstrap Carousel Control by replacing the default navigation arrows with stylish arrows featuring circle backgrounds

Looking to update the appearance of the carousel icons in Bootstrap 4? How about changing them from simple arrows to arrows with dark semi-opaque circles underneath? If you're wondering how to achieve this modification, keep in mind that the icons ar ...

Is the node certificate store limited to reading only from a predefined list of certificates?

Is there a way to add a new certificate to the list of certificates node trusts, even after some struggle? It appears that Node only trusts certificates hardcoded in its list located here: https://github.com/nodejs/node/blob/master/src/node_root_certs.h ...

Include an HTML attribute within a given string

Using jQuery, I am adding HTML content to a div. The variables rowString and inputString have been defined beforehand: $("#filterContainer").append( rowString + `<label class='filterLabel' for=${filter}>${filter}< ...

What steps do I need to take to develop a syntax similar to Vue.js using only plain JavaScript?

<div id=""> <span>{{msg}}</span> </div> Assume that {{msg}} is a variable in JavaScript. Now, I aim to locate the parent tag of {{msg}} and replace its content with a new value using innerHTML, where {{msg}} serves as an identi ...

Is there a way to obtain asynchronous stack traces using Node.js and TypeScript?

When working with TypeScript, I encountered an issue with stack traces. It seems that only the bottommost function name is displayed. My setup includes Node.js v12.4.0 on Windows 10 (1803). Below is the code snippet: async function thrower() { throw new ...

Uploading a file to an MVC controller using AJAX is unsuccessful

When posting a form that contains file and HTML data, along with a function to get geocode, the controller only receives the data from the AJAX post but not the file. I suspect it may have something to do with the button used for posting, but I'm unce ...