The Javascript function is not functioning properly within the form loop

JavaScript only works in the first iteration and does not affect the fields from the second iteration.

Sample Code Using forloop

 {% for i in userlist %}
    <input id="a" type="email" value="{{i.email}}">
    <input id="b" type="text" value="{{i.date_of_birth}}">
    <input id="c" type="text" value="{{i.mobile}}">
 {% endfor %}

Button to Disable Editing

<button onclick="disableProfileEditing()" type="button"> Disable </button>

Button to Enable Editing

<button onclick="enableProfileEditing()"> Edit</button>

JavaScript Functions

function disableProfileEditing() {
    document.getElementById(a).disabled = true;
    document.getElementById(b).disabled = true;
    document.getElementById(c).disabled = true;
}


function enableProfileEditing() {
    document.getElementById(a).disabled = false;
    document.getElementById(b).disabled = false;
    document.getElementById(c).disabled = false;
}

Answer №1

Regardless of how the for loop is structured, it creates multiple elements with the same ID, causing issues. It would be better to assign them a unique class or data attribute, but using a class is simpler and more widely supported. Then in your function, you can target all elements with that class (or data attribute) to perform actions such as hiding.

So instead of using IDs in the for loop, change them to classes to allow for multiple instances. Subsequently, modify the first function to target all elements with each class accordingly.


 {% for i in userlist %}
    <input  class="email" type="email" value="{{i.email}}">
    <input class="dob" type="text" value="{{i.date_of_birth}}">
    <input class="mobile" type="text" value="{{i.mobile}}">
 {% endfor %}

In the revised function:

function disableProfileEditing() {
    Array.apply(0,document.getElementsByClassName("email")).forEach(x=> x.disabled = true);
    Array.apply(0,document.getElementsByClassName("dob")).forEach(x=> x.disabled = true);
    Array.apply(0,document.getElementsByClassName("mobile")).forEach(x=> x.disabled = true);
}

An alternative approach could involve creating a container div with a unique ID and having the for loop add elements inside that. This might simplify handling the visibility of elements collectively.

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

Tips for resolving the [vue/no-use-v-if-with-v-for] warning in Vue

I am encountering an issue with a div element that supports v-for and v-if. The output is correct, however, there is a warning that I find quite annoying: [vue/no-use-v-if-with-v-for] The 'prit_type_ids' variable inside the 'v-for' dir ...

How can you retrieve the property value from an object stored in a Set?

Consider this scenario: SomeItem represents the model for an object (which could be modeled as an interface in Typescript or as an imaginary item with the form of SomeItem in untyped land). Let's say we have a Set: mySet = new Set([{item: SomeItem, s ...

Can the title of a page be modified without using HTML?

Is it possible to update the title of my website directly from the app.js file? (I am utilizing node.js and express.js) ...

What is the best way for me to determine the average number of likes on a post?

I have a Post model with various fields such as author, content, views, likedBy, tags, and comments. model Post { createdAt DateTime @default(now()) updatedAt DateTime @updatedAt id String @id @default(cuid()) author U ...

Seeking guidance on configuring the layout of Many-To-Many Fields within Django

Developing a REST-API for an Angular application that will be used on my guitar company’s website. The Artist Profile page will showcase the artist's name, a brief bio, and a list of projects (bands) they are part of along with the respective date-r ...

The Firefox dropdown menu constantly reverts back to the default option because of JavaScript running in AngularJS

I am currently developing an AngularJS app and encountering issues with select dropdown menus specifically in Firefox. Whenever I click on a select menu and hover over the options, it automatically resets the selected option back to the default/first opti ...

What should I verify if the Grails application is not loading on IE9 exclusively?

In the process of developing a Grails project that incorporates some JS code, I encountered an issue where the project ran smoothly on Google Chrome (v34.0.1847.116 m) and Mozilla Firefox (v28.0), but failed to start on IE (v9.0.23), resulting in a blank s ...

Cut and paste functionality for ag grid the cutting action

I am looking to enable copy, cut, and paste actions in ag grid. While ag grid enterprise features include everything I need, the cut action is missing. I believe it can be implemented by adding a keydown event handler to the component. The process would ...

What is the correct way to invoke a function expression that is nested within another function?

Is it possible to call a function expression that is nested within another function in JavaScript? let x = function() { //perform some tasks let y = function() { console.log('Greetings Earthlings!') } } x(); ...

When adding the input text value to the <canvas>, the output of .appendTo('<p>' + value + '</p>') is not being shown

Check out my jsfiddle: https://jsfiddle.net/gemcodedigitalmarketing/zn5yLwh3/ I'm trying to append the text from the customText input to the canvas, but it doesn't seem to be working. Yesterday, I successfully appended td and tr to a table, so ...

The size of the card image and content area will remain constant based on the specified percentage

Looking for some guidance as I am still learning. I need the card below to have a fixed width of 38% for the image area and 62% for the content area, regardless of the size of the content (the height can increase if there is more text). In the image above ...

Tips on conducting a statistical analysis without having to wait for the completion of an AJAX response

I am looking to track the number of clicks on a specific div with the id #counter and then redirect the user to a different website. To achieve this, I have implemented an ajax call on the click event of the #counter div. Upon successful completion of the ...

working with Selenium in the Chrome web browser

Within a file named e2e.js, the following code was written: const webdriver = require('selenium-webdriver'); const driver = new webdriver.Builder().forBrowser('chrome').build(); driver.get('https://www.google.co.il/'); I h ...

Tips for dynamically adding an external SVG animation to your website:

When trying to insert an animated SVG using jQuery or plain JavaScript, they appear static in Chrome and Edge, but display correctly in Firefox: $(".loader").prepend("<svg><use xlink:href='/images/icons.svg#loading-ring'></use> ...

Identifying proxy-induced errors in the request module of node.js: A step-by-step guide

Is the error being caused by a proxy connection issue? If so, I may need to try using a secondary proxy. I intentionally set the wrong address to trigger an error, and upon checking the error object, I found that it contains {code: 'ECONNRESET'} ...

When we find ourselves within a fat arrow function

I'm struggling with this code. I have a ternary operator within a fat arrow function, but for some reason it's not working. There are no errors in browserify or the console, but the headers are not being printed. If I remove the {} and ternary o ...

Navigating attributes originating from the key in JSON: A guide to effective management

I'm facing a situation in my application where I have a JSON object structured like this: var pages = { home: { title: "Home", description: "The home page", file: "home.html", url: "/home" }, blog: { ...

Issue identified in the sharing of HTML content across two separate domains

I have a Django web service application running on domain A. Within this application, there is a content file that stores both HTML files and images required for functionality. Another application on domain B needs to access the services and content from m ...

"Utilizing GroupBy and Sum functions for data aggregation in Prisma

I am currently working with a Prisma schema designed for a MongoDB database model orders { id String @id @default(auto()) @map("_id") @db.ObjectId totalAmount Int createdAt DateTime @db.Date } My ...

Utilizing an undefined constant in angular programming may lead to unexpected errors

Seeking assistance in generating random first and last names based on gender for a form using Angular. I am relatively new to Angular and keep encountering this error whenever the Use of undefined constant firstName - assumed 'firstName' Here ...