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

Can Next.js 13 components maximize performance by utilizing server and client components simultaneously? What is the best approach to achieve this?

Introduction Currently, I am exploring server and client components in Next.js 13 and looking to incorporate them into my project. One of the key features is a container component that utilizes react-intersection-observer to track which section is visible ...

What is the best way to add a CSS rule to JavaScript?

animation: scaleUp 0.3s linear 0.4s forwards; animation: scaleDown 0.3s linear forwards; Greetings! I'm currently working on adding animations to my content filtering functionality. Specifically, I want to incorporate the aforementioned CSS rules in ...

Unraveling the Perfect Jest Stack Trace

Currently, I am in the process of debugging some tests that were written with jest using typescript and it's causing quite a headache. Whenever a test or tested class runs Postgres SQL and encounters an error in the query, the stack trace provided is ...

Choosing read-only text fields using JQuery

I am working on an ASP.NET MVC project and I am looking to select all text boxes with the "readOnly" attribute on the current page. Once identified, I want to trigger a modal jQuery dialog on keypress for each of these disabled text boxes. Any suggestion ...

Unable to transfer bootstrap form data from the view to the controller due to issues with bootstrap validations

Scenario I have integrated a bootstrap form into my codeigniter application with bootstrap validation to ensure data accuracy. I want the submit button to work properly so that users can successfully submit the form and be redirected to the action page ...

Can someone help me understand why this AJAX script is returning a status code of 404?

After getting involved with AJAX and utilizing the MAMP web server, I decided to work on a simple script to test its functionality. My attempt led me to investigate using the status property of XMLHttpRequest(); As it turns out, the issue I encountered was ...

What is the optimal method for delivering HTML content in a Node.js application using Express.js?

My current approach involves serving all HTML content directly from my app.js/server.js file, as shown below: app.get('/', function(req, res) { res.render('index.html'); }); app.get('/about', function(req, res) { res. ...

JavaScript event/Rails app encounters surprising outcome

I have encountered a strange bug in my JavaScript code. When I translate the page to another language by clicking on "English | Русский" using simple I18n translation, my menu buttons stop working until I reload the page. I suspect that the issue ...

What methods are available in JavaScript regex for validating city names?

var cityRegex = /^[a-zA-z] ?([a-zA-z]|[a-zA-z] )*[a-zA-z]$/; is the regular expression I attempted to create. However, it fails when inputting a city name like "St. Petersburg." Update: It seems challenging to create a perfect regex pattern for city name ...

Problem with targeting the .prev() and closest() class of a text input box

Could you please review This Demo and advise why I am unable to select the first .fa class before the text box #name ? This is what I have been trying: $(this).prev().closest(".fa").addClass("err"); within this code block <div class="row"> & ...

Issues with HTML formatting in PHP emails

I am sending an approval/disapproval email to a user. I want to include a button in the email so that when the user clicks it, they can approve or disapprove the request. However, I am facing an issue as I cannot see the button in the mail when I receive ...

Unable to locate module: '@material-ui/pickers' - Material UI React

I encountered an error that said: Material UI React - Module not found: Can't resolve '@material-ui/pickers' in React. Previously, I faced a similar issue with '@date-io/date-fns' but was able to fix it by updating to the latest ...

Having trouble with `request.auth.session.set(user_info)` in HapiJS?

I've encountered an issue with my strategy that is defined on a server.register(). Although I followed a tutorial, the code seems to be copied verbatim from it and now it's not functioning as expected. server.auth.strategy('standard&apo ...

Generate a compilation of products developed with the help of angularjs

I have a request to make a list of items using Directives and share them through controllers. Check out my code example on plunker: Code Example Below is the JavaScript code: var app = angular.module('app', []); app.controller("BrunchesCtrl", ...

What is the best approach for assigning a value to the action URL in el-upload?

<el-upload class="upload" action="http://127.0.0.1:5000/upload/email" :file-list="fileList" > Utilizing the Element UI library, I am attempting to pass an email value to the 'action' URL in the format of base_ ...

Schema-specific conditions for JSON data

I have been experimenting with the if-then-else statement in JSON, but I am encountering some issues with it. { "type": "object", "minProperties": 2, "maxProperties": 2, "properties": { "human": { "enum": [ "Kids", "Ad ...

How can I move a TableItem from one material UI component to another using drag-and-drop?

I am facing an issue where I need to drag a ListItem from one List component to another. I am uncertain about how to accomplish this in Material UI. ...

Is there a way to create a duplicate form without any pre-filled text when clicking the "next" button using JavaScript?

This form contains the details that I would like to display on the page again when clicking the "Add Another Module" button. <div> <form class="in-line" id="module_info"></form> <div style="display: flex;"> < ...

Getting the value of a variable within the scope of AngularJS can be achieved by utilizing

I have an ng-repeat directive in my code that displays slides. Here is a snippet of the data: slides = [{ src: "/sikiosk/slidedata/Global/NA/USNS/Cafeteria/5000_24.jpg", interval: 5000 }, { src: "/sikiosk/slidedata/Global/NA/USNS/Cafeteria/5000_login-regi ...

Having trouble making the swing effect trigger on mouseover but not on page load

I am trying to achieve a swinging effect on mouseover only, not on page load. Below is the JS code I have: (function swing() { var ang = 20, dAng = 10, ddAng = .5, dir = 1, box = document.getElementById("box"); (function setAng(ang){ ...