What is the best way to choose the unique identifier of an HTML element inside a for loop in a Django template?

I need help selecting an HTML button that is generated within a for loop in a Django template using JavaScript. How can I assign a unique ID to each button and select it correctly in JavaScript? Currently, all buttons have the same ID within the loop, resulting in no action when clicked.

html

% for post in page_obj.object_list %}
            <div class = "individual_posts">
                <a href="{% url 'username' post.user %}"><h5 class = "post_user">{{ post.user }}</h5></a>
                <h6 id = "post_itself">{{ post.post }}</h6>
                {% if post.user == request.user %}
                    <button id="editButton" class="edit_button">Edit</button>
                {% endif %}
            </div>
        {% endfor %}

JavaScript

document.addEventListener('DOMContentLoaded', function(){
    document.querySelector('#uniqueIdHere').onclick = edit_email();
})

Answer №1

To distinguish your buttons, consider adding the forloop counter to their HTML id:

id="editButton{{ forloop.counter0 }}"

This way, you can easily target the specific button in your JavaScript code.

If you want to apply onclick functionality to all buttons, update your selector in the JS from # to ('.edit_button') for it to work universally.

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

Unable to add new tags in Vue multiselect component

Currently, I am utilizing a Vue Multiselect instance with two functions. One function interacts with the database to provide autocomplete functionality, which is working successfully. The second function allows for adding new tags that are not present in t ...

looping through an ajax function with addEventListener

Apologies in advance for any errors in my English. My task involves creating a simple webpage with just 2 links. When one of these links is clicked, it should load the content of a specific .html file on the same page. For example: clicking on link 1 (wi ...

Excessive requests to location or history APIs in a brief period of time

Alert: Reached maximum update depth. This issue may arise when a component invokes setState within useEffect without a dependency array, or if any of the dependencies change on each render. const OwnerPage = () => { const onOpen = useAgencyModal((s ...

Is it possible to define key strings as immutable variables in JavaScript/Node.js?

Having transitioned from the world of Java to working with Node.js + AngularJS for my current project, I have encountered a dilemma. There are certain "key Strings" that are used frequently in both client and server-side code. In Java, it is common practi ...

Having trouble serving static files with express.Router?

With my file system becoming more complex, I decided to switch from using app.use(express.static()) to utilizing express.Router(). Initially, I thought I could just replace app.use(express.static()) with router.use(express.static()), but unfortunately, thi ...

React: Implementing localStorage token addition in loginHandler function using State hook is not functioning as expected

I've implemented an AuthContextProvider in my React application to handle user authentication and logout functionality: import React, { useState } from "react"; import axios from "axios"; import { api } from "../api"; co ...

Encountering an issue when bundling an application using electron-forge: "Unable to find solution for './→' "

Having trouble packaging my Electron application using electron-forge. It seems like the issue lies with native modules such as 'sqlite3'. Upon running the command npm run package, I encounter this error: Module not found: Error: Can't reso ...

What is the reason behind fullstack-angular generator utilizing Lo-Dash's merge rather than document.set?

This is the original code snippet used for updating: exports.update = function(req, res) { if(req.body._id) { delete req.body._id; } Thing.findById(req.params.id, function (err, thing) { if (err) { return handleError(res, err); } if(!thing) { ...

Struggling with configuring a 'post' endpoint in an express server problem

My goal is to validate that my client is able to successfully post information to its server. I have configured a specific 'route' on my Express server for this purpose. // server.js this is the server for the PvdEnroll application. // var ex ...

I would like to include the value of the "file_id" variable in the href attribute of an appended HTML element, but it seems

<div id="invite_popup"> </div> $(".invite_button2").click(function(){ var file_id = $(this).data("id"); //alert(file_id); var popup2 ='< ...

One simple click to auto-fill the form

I have encountered a problem that has been discussed before, but my lack of coding knowledge is making it difficult for me to find a suitable solution that matches the code on my website. The issue at hand is as follows: I need my form to populate car mak ...

Utilize CSS to format the output of a script embedded within

When I embed the following script in my HTML, the output doesn't have any styling. How can I style the script output to blend well with the existing HTML structure? I tried accessing the output by ID, but couldn't figure it out. <script> ...

Has xlink:href become outdated for svg <image> elements?

In the realm of SVG attributes, it is noted by MDN xlink:href that href should be used over xlink:href. Interestingly, on the svg example page, last revised on July 6, 2017, the attribute utilized in the given example is xlink:href. The question arises: ...

Creating a Route in Angular 2 for a Component other than the one initialized with the bootstrap function

I am currently in the process of working on a project involving Angular2. If you are interested in understanding why I need to do what I am about to explain, please take a look at this issue. The main component in my project is called AppComponent and it ...

Error: An unexpected symbol '<' was encountered after the build process in Vue.js

I just finished deploying a MEVN stack application to heroku. While everything is functioning properly locally, I am encountering a blank page and the following errors in the console post-deployment: Uncaught SyntaxError: Unexpected token '<' ...

My React app experienced a severe crash when trying to render an animation in L

Currently, I am working on a React application that was set up using Vite. I recently incorporated an animation using Lottie, and although I was successful in implementing it, I encountered a problem when navigating between different pages of my applicati ...

Sequentially iterate through elements based on their Data attributes

Assume you are working with HTML elements like the ones shown below <span class="active" data-id="3"> Test 3 </span> <span class="active" data-id="1"> Test 1 </span> <span class="activ ...

Error: JSONResponse is missing a semicolon before the statement in the syntax

I encountered the following error: SyntaxError: missing ; before statement Although I am unsure of what is causing this error, here is the code snippet that I am currently working with: (function pollschedule(){ $.ajax({type: "GET", dataType: "j ...

PHP displaying incorrect value after modifying value in JavaScript

One issue I am facing is with an html page that submits a form through javascript. Prior to the submission of the form, I modify the value of a hidden tag, which should then be retrievable in php. However, when attempting to retrieve the value in php, it a ...

In order to properly set up an AutoNumeric object, it is essential to have at least one valid parameter provided

I've been working with the AutoNumeric library in my Vue js V2 application and keep encountering a specific error message in the console Issue with mounted hook: "Error: At least one valid parameter is needed to initialize an AutoNumeric object& ...