Issue with accessing the response object and dynamically generated HTML elements beyond the function in Javascript

I am in the process of developing a todo application using Django and Ajax. Upon loading, I retrieve all tasks from the database and display them. When a user clicks on a task, my goal is to mark it as completed. However, I am encountering the following issues:

  1. I am struggling to access dynamically generated HTML elements and the response object outside of the buildList() function.
  2. When I add an event listener to a task (span element with class = title), I am unable to access the task object in order to send it to the backend using an Ajax request and manipulate it accordingly.

todo.js

buildList()

function buildList(){
    var wrapper = document.querySelector("#list-wrapper")
    wrapper.innerHTML = ''
    var xhr = new XMLHttpRequest()
    xhr.open('GET', 'http://127.0.0.1:8000/api/task-list/', true)
    xhr.onload  = function(){
        if(this.status==200){
            var list = JSON.parse(this.response)
            for (var i in list){
                var item = `
                    <div id="data-row-${i}", class="task-wrapper flex-wrapper">
                        <div style="flex:7">
                            <span class="title">${list[i].title}</span>
                        </div>
                        <div style="flex:1">
                            <button class="btn btn-sm btn-outline-info edit">Edit</button>
                        </div> 
                        <div style="flex:1">
                            <button class="btn btn-sm btn-outline-dark delete">-</button>
                        </div>
                    </div>
                `
                wrapper.innerHTML += item
            }

            for(i in list){
                var tasks = document.querySelectorAll('.title')
                tasks.forEach(function(el, list){
                    el.addEventListener('click',()=>{
                        console.log(list[i])
                    })
                })


            }
        }
    }
    xhr.send()
}

// Adding a Task //
var form = document.querySelector("form")
form.addEventListener('submit', (e)=>{
        e.preventDefault()
        var title = document.getElementById('title').value
        var xhr = new XMLHttpRequest()
        xhr.open('POST', 'http://127.0.0.1:8000/api/task-create/', true)
        xhr.setRequestHeader('Content-type','application/json')
        xhr.setRequestHeader('X-CSRFToken',csrftoken)
        xhr.onload = function(){
            if(this.status==200){
                buildList() 
                document.getElementById('form').reset()
            }
        }
        xhr.send(JSON.stringify({"title":title}))
    }
)

// Marking a task as complete //
function taskComplete(e){
    console.log(e.target)
}

index.html

<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <link href="https://fonts.googleapis.com/css?family=Montserrat&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="{% static 'styles.css' %}">
    <title>To Do</title>

</head>
<body>
    <div class="container">

        <div id="task-container">
            <div id="form-wrapper">
                <form id="form">
                    <div class="flex-wrapper">
                        <div style="flex: 6">
                            <input id="title" class="form-control" type="text" name="title" placeholder="Add task">
                        </div>
                        <div style="flex: 1">
                            <input id="submit" class="btn" type="submit" >
                        </div>
                    </div>
                </form>
             </div>

            <div id="list-wrapper">

            </div>  
        </div>
    </div>
</body>
<script src="{% static 'todo.js' %}"></script>
</html>

Answer №1

Upon inspecting your code, it seems that you are trying to reference the variable list when adding an event listener. However, in this specific context, list is actually being assigned to a callback argument. To resolve this issue, I recommend renaming the callback argument so that you can access list from the parent scope.

 items.forEach(function(item, idx){

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

The React map component isn't appearing on the screen once it has been rendered

I stumbled upon a functional example of Google Maps integration in React over at https://github.com/StephenGrider/ReduxCasts within the weather project. To set it up, simply run npm i; npm start In my own https://bitbucket.org/codyc54321/anthony-project-r ...

Why isn't the DIV I created in JavaScript appearing when the page loads?

I've been struggling to get the DIV generated by the Javascript code, particularly in the function parameter id within creatediv('xdiv', html, 100, 100, 10, 10) where id = 'xdiv'. <!DOCTYPE html> <html> <head> &l ...

How can I pass props from a custom _app.js file to the <Navbar> component in Next.js?

How do I go about passing props to a Navbar component that will be included under the Head component? Although I successfully passed props in the index.js page using getServerSideProps, it seems to not work properly in the _app.js file. import ".. ...

Retrieve the chosen date from a DatePicker using a Javascript function

Is there a way to retrieve the user-selected date using a JS function? I attempted this method: var test = $("#datepicker").datepicker( 'getDate' ); However, when I display it with an alert, it shows [object object] instead of the date. This ...

Unable to complete 'drawImage' operation in react-image-crop

I'm currently working on cropping an image with the 'react-image-crop' package and storing the output in the result variable. import React, { useState } from 'react' import ReactCrop from 'react-image-crop' import ' ...

Animating along a predetermined L-shaped route using the MotionGuide tool for tweening

Exploring Tween.js for basic animation has been an exciting journey. To create a ball moving along a predefined path, it appears that the MotionGuide plugin is necessary. You can find detailed information about it here: I am interested in having my objec ...

Counting Slides in a Slick Carousel

I am currently working with the slick carousel in React.js using ES6 and I'm having trouble getting the slide count. In my function, I can successfully retrieve the count inside the event listener but outside it returns null. Can someone point out wha ...

How to choose the placeholder element in Svelte?

I'm currently working on adding a placeholder to a select element, but I'm encountering an issue. When I include the selected attribute for the first option, it displays as an empty space. <select> {#if placeholder} <option v ...

What is the best way to confirm if the elements in an array are in consecutive order?

Is there a way to determine if an array's members are consecutive? For instance, the array [1,3,4,5,6] is not considered consecutive because it is missing the number 2 in the sequence. Which JavaScript array methods can be used to check for this type ...

Are foreign characters the culprit behind the JSON parsing problem?

I am encountering an issue while attempting to parse a field containing JSON data returned from an API. The data includes various unusual characters like East Asian symbols and curly quotes, causing this error to appear. I am unsure of how to resolve it - ...

Ways to superimpose images

Everything seems to be functioning correctly in my code, but I would like the output images to overlap slightly. This could possibly be achieved using margins, padding, or some other script. Additionally, is there a way to incorporate z-index so that the ...

The Angular Table row mysteriously vanishes once it has been edited

Utilizing ng-repeat within a table to dynamically generate content brings about the option to interact with and manage the table contents such as edit and delete. A challenge arises when editing and saving a row causes it to disappear. Attempts were made ...

Refresh all $(document).ready(); functions after AJAX has finished loading

I find myself in the midst of customizing an application where my access is limited to just one CSS file and one JS file. Unfortunately, I cannot modify the existing markup or scripts, which leaves me with the challenge of adding my own styles and function ...

Dynamically shift the table footer to the bottom of a scrolling div by utilizing jQuery

I'm facing a challenge where I need to relocate each th tag from the footer row of a table to the bottom of a scrolling div. You can check out the scenario on this link. Currently, I am able to achieve this by hardcoding it like so: $('.sticky- ...

Accessing data from arrays containing objects through an AJAX Request

I am trying to work on an ajax request, but I'm struggling with it. Here is the current ajax call I have: $.ajax({ type: 'GET', url: 'https://teamtreehouse.com/garrettsanderson.json', dataType: 'json', success: f ...

Mastering parameter passing in Node.js functions: A comprehensive guide

As I embark on my journey with node js (refer to the question), please be patient as I navigate through this new territory. To clarify my query, I have developed a function to be invoked in another JS file: exports.test = function(req, res){ connection ...

Utilizing Angular to automatically extract keys from nested objects in a response

In my Angular application, I am facing a challenge with accessing nested responses from the server. The data structure contains multiple responses within one parent object, and I am struggling to dig deeper into it. Here is the code snippet I have so far: ...

Encountered an issue with setting the property of "something" to undefined when attempting to generate an array sorted by dates

After seeking help from @Kato on Stack Overflow regarding sorting a Firebase AngularFire array into weeks and days, I encountered an error where I cannot set a property of "something" that is undefined. To provide more context, I created a detailed Plunke ...

Error encountered: Element cannot be clicked on at specified coordinates - Angular/Protractor

Recently, I have been testing out CRUD functionality in an Angular app using Protractor. One recurring issue I've encountered is with the create/edit buttons, which all open the same modal regardless of the page you're on. The frustrating part i ...

Upgrade the WordPress light editor to the advanced version

After developing a script to upgrade the WordPress editor on a specific page from light mode to Advanced once a user clicks the Unlock button and confirms their desire to make the switch, an issue arose. Despite deducting 5 coins from the user's balan ...