Number each element in sequence

Looking to give sequential numbering to elements by iterating through them.

For instance, if there are 6 input elements, the goal is to update their names correspondingly like "name=input1", "name=input2", and so on. This involves using a for loop to reassign names each time an element is added or removed.

Below is the function that's attempted (and struggling) to be executed:

function count(){
    console.log(numChildren)
    var childCount = document.getElementById("items").childElementCount;
    console.log(childCount + " = number of children")
    numChildren = [];
    for (var i = 0; i < childCount; i++) {
        numChildren.push(i+1)
        document.querySelector("input[name*='item_name_']").name = "item_name_" + numChildren[i];
    }
};

Answer №1

If you're looking for a solution, you could try something along the lines of:

const elements = document.getElementById("items").children;
        
 for (var j = 0; j < elements.length; j++) {

       elements[j].setAttribute('title', 'element_title_'+(j+1));

  }
<html>

<body>
    <div id="items">
        <input type="text" title="element_1" />
        <input type="text" title="element_2" />
        <input type="text" title="element_3" />
        <input type="text" title="element_4" />
    </div>
</body>
</html>

Answer №2

If you want to modify the names of certain input elements in a collection, you can easily achieve this using a forEach loop and referencing the index as you iterate through each element.

  let inputs = document.querySelectorAll("#items input[name*='item_name_']");
inputs.forEach((el, index) => { el.setAttribute('name', 'item_name_'+index); })
<div id='items'>
  <input type='text' name="item_name_99" />
  <input type='text' name="item_name_19" />
  <input type='text' name="item_name_8" />
  <input type='text' name="item_name_3" />
  <input type='text' name="item_name_49" />
  <input type='text' name="item_name_9" />
</div>

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

What are the steps to perform typecasting in nodejs?

Struggling with converting string values to numbers and encountering an error. const express=require('express'); const bodyParser=require('body-parser'); const app=express(); app.use(bodyParser.urlencoded({extended:true})); app.get(&qu ...

The property is returning an empty string, but the function is functioning perfectly

Check out this related Stack Overflow post exports.getAddress = asyncHandler(async (req, res, next) => { var lon = req.query.lon; var lat = req.query.lat; var formattedAddress = ""; var url1 = 'url' request(url1 ...

Obtaining a pdf file using javascript ajax is a straightforward process

Looking to access my JavaScript file generated by a microservice (byte[]): public int retrieveLabel(Request request, Response response) throws IOException { response.header("Access-Control-Allow-Origin", "*"); ArrayList<JSONObject> orders = ...

a service that utilizes $http to communicate with controllers

My situation involves multiple controllers that rely on my custom service which uses $http. To tackle this issue, I implemented the following solution: .service('getDB', function($http){ return { fn: function(){ return $http({ ...

Changing an AngularJS Protractor promise from a string to a decimal number - how to do it?

I am currently working with Angular.js Protractor to retrieve the values of cells in a grid. Although I can successfully retrieve these values, they are strings and I need to perform calculations with them. Upon attempting this: ptor.findElements(protrac ...

Is there a way to access specific methods within a JavaScript file?

Within my javascript assets folder, I have a file named jstester.js that looks like this: function hehe() { alert("wedsdsd"); } document.write("fdygsdfysdgf"); Then in the main index.html file in the public directory, I include the following code: & ...

The issue arises when DataTable fails to retrieve the ID element following a page transition

I am facing an issue with making ajax calls on focus for each text input. I am able to do it on the first page, during document ready event. However, when I navigate to another page, JavaScript is unable to parse the inputs as they were not created during ...

Guide to creating individual column templates in Kendo-UI grid

I recently started using Kendo-UI in my project and wanted to have a column in my grid display an image button along with a field, similar to the 'Contact Name' column in the documentation here. After exploring the documentation, I came across th ...

Unable to save or create files in Store.js

Recently, I've been trying to save a file on client storage using Store.js. After changing the date with store.set and logging it to the console successfully, I encountered an issue where the data was not being saved in the app directory as expected. ...

How to eliminate unnecessary space when the expansion panel is opened in material-ui

Is there a way to eliminate the additional space that appears when clicking on the second accordion in material UI? When I open the second accordion, it shifts downward, leaving a gap between it and the first accordion. Any suggestions on how to remove thi ...

Error being thrown in Express/Mongoose not being caught and handled

While using Postman to test my APIs, I'm encountering an issue with mongoose. It seems that when I use throw new Error() within the userSchema, the error does not get caught by the route.post. How can I ensure that errors thrown using throw new Er ...

typescript error: passing an 'any' type argument to a 'never' type parameter is not allowed

Encountering an error with newUser this.userObj.assigned_to.push(newUser);, receiving argument of type 'any' is not assignable to parameter of type 'never' typescript solution Looking for a way to declare newUser to resolve the error. ...

What is the best way to traverse through a nested JSON file with d3.js?

Greetings. I am currently facing a challenge in navigating through a nested JSON file. Below is the JSON data that I need assistance with: {"Id":466,"Name":"korea", "Occurrences": ...

Are there any substitute proxy servers that are capable of bypassing CORS restrictions using local IP addresses?

Successfully bypassing CORS for AJAX requests to public IP addresses using proxy servers has been a game-changer. Is there a similar approach that can be utilized for local IP addresses when the server is hosted off-site? Unfortunately, I lack the abilit ...

Updating textures dynamically for individual faces in a three.js environment

I have been facing a difficult challenge for some time now, struggling to achieve my goal while unsure if I am on the right path. The Objective My current project involves developing a three.js web application that loads JavaScript models and assigns cu ...

Implementing meta tags in React.js

I am attempting to incorporate dynamic meta-tags on each page of my website. However, despite my efforts, I cannot seem to locate the meta-tags in the page's source code. Do I need to make adjustments in public/index.html, considering that I am not ut ...

Issue with Material UI React JS Select component: Unable to deselect multiple values when more than one item is selected

Implementing a multiselect dropdown in material ui with specific conditions: The dropdown will contain [0 Apples, 1 Oranges, 2 Grapes]. By default, 0 Apples should be selected. None of the options can be unselected. If 0 Apples is selected and the user se ...

The variable 'props' is given a value but is never utilized - warning about unused variables in Vue 3

Within my Vue component file, I am using the following code: <template> <router-link :to="{ name: routerName }" type="is-primary" class="inline-flex justify-center py-2 px-3 mb-3 border border-transparent shado ...

Exploring the process of obtaining a collection of JSON sub-items and using Angular's method for finding a match within an array

Question 1 In my program, I am receiving a JSON object called scope.tagSet, which has the structure shown below. { Tags : [ {"TagID" : "ID1" , "TagName" : "Name1"}, {"TagID" : "ID2" , "TagName" : "Name2"}, {"TagID" : "ID3 ...

The function `map` cannot be applied to `this.state.[object]`

It seems like I might be overlooking a simple mistake, but I keep encountering this.state.iata.map is not a function , even though I have bound the context to all functions where I need to access that state. Additionally, the iata state is an array, s ...