JavaScript code not functioning properly when accessing all information retrieved from Django Model

When I retrieve the endDate field from a Django model using a for loop on an HTML page, I want to verify if all the end dates are earlier than today's date. To achieve this, I am utilizing JavaScript code.

Although my code successfully checks the first retrieved date, it fails to work on subsequent dates.

Below is my HTML code for fetching data:

{% for p in object_list %}
    <h4>{{ p.jobName }}</h4>
    <p><b style="color: red">Expires On: </b><b>{{ p.endDate }}</b></p>

    <a href="{{ p.get_absolute_url }}" target="_blank">View info</a>    

    <input type="hidden" id="endDate" name="variable" value="{{ p.endDate }}">
    <span id="check"></span>            

{% endfor %}

JavaScript code for date verification:

<script type="text/javascript">       
    var endDate = document.getElementById("endDate").value;
    var ToDate = new Date();
    if(new Date(endDate).getTime()<=ToDate.getTime()){
        document.getElementById("check").innerHTML = "Expired";
        document.getElementById("check").className = "label danger";
    }
    else{
        document.getElementById("check").innerHTML = "Active";
        document.getElementById("check").className = "label success";
    }
</script>

Currently, I have 2 {{ p.jobName }}. The first one should display as Expired, while the second should show as Active. However, my code only works correctly for the first date (Computer Admin).

This is the output I'm currently receiving: https://i.sstatic.net/MptWt.png

Could someone identify what might be causing this issue?

Thank you

Answer №1

Adding on to the points mentioned in the previous discussions:

The core issue lies within this section of your code:

{% for p in object_list %}
...   
    <input type="hidden" id="endDate" name="variable" value="{{ p.endDate }}">
    <span id="check"></span> 
...
{% endfor %}

In HTML, each element can only have a unique ID attribute. Having multiple elements with the same ID like "endDate" and "check" is not valid as per HTML specifications. This leads to errors in your JavaScript functionality because when there are multiple elements with the same ID, functions like document.getElementById expect only one element to be returned.

To fix this issue, you need to change the IDs to classes (e.g., from id="endDate" to class="endDate") and update your JavaScript accordingly. Instead of using getElementById, utilize getElementsByClassName, which returns a collection that can be iterated over with .forEach. Additionally, ensure you target the adjacent .check span correctly. The below code snippet demonstrates how you can modify your script to handle this situation:

var endDateElts = Array.from(document.getElementsByClassName("endDate"));
var currentDate = new Date();

endDateElts.forEach(function(dateElt) {
    var endDate = dateElt.value;
    var check = dateElt.nextSibling;
    if(new Date(endDate).getTime() <= currentDate.getTime()){
        check.innerHTML = "Expired";
        check.className = "label danger";
    }
    else{
        check.innerHTML = "Active";
        check.className = "label success";
    }
});

Answer №2

After evaluating

{% for p in object_list %}
    <h4>{{ p.jobName }}</h4>
    <p><b style="color: red">Expires On: </b><b>{{ p.endDate }}</b></p>

    <a href="{{ p.get_absolute_url }}" target="_blank">View info</a>    

    <input type="hidden" id="endDate" name="variable" value="{{ p.endDate }}">
    <span id="check"></span>            

{% endfor %}

It seems that there are multiple objects sharing the same ID, causing the JavaScript to only affect the first instances of endDate and check.

<input type="hidden" id="endDate" name="variable" value="{{ p.endDate }}">
<span id="check"></span> 

Suggested approach:

  1. Utilize document.querySelectorAll() to target multiple DOM elements with identical classes.
  2. Iterate through the NodeList and execute desired operations on each element.

const endDates = document.querySelectorAll('.endDate');
const checks = document.querySelectorAll('.check');
let ToDate = new Date();
let i = 0;
for (const endDate of endDates){
    if(new Date(endDate.value).getTime()<=ToDate){
      checks[i].innerHTML = "Expired";
      checks[i].className = "label danger";
    }
    else{
      checks[i].innerHTML = "Active";
      checks[i].className = "label";
    }
    i++;
}
<div class="container-1">
<input type="text" class="endDate" name="variable" value="2019-11-29">
<span class="check"></span>
<br>
</div>
<div class="container-2">
<input type="text" class="endDate" name="variable" value="2019-11-24">
<span class="check"></span>
<br>
</div>
<div class="container-3">
<input type="text" class="endDate" name="variable" value="2019-11-27">
<span class="check"></span>
</div>

Additional information: If feasible, consider handling the validation in the backend views.py rather than the front-end. This will streamline the process and allow for cleaner manipulation and presentation of data. The suggestion made by @Robin Zigmond to perform this action server-side is worth considering.

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 some effective methods for selectively handling batches of 5-20k document inputs when adding them to a collection containing up to one million documents using MongoDB and Mongoose?

My MMO census and character stats tracking application receives input batches containing up to 5-20k documents per user, which need to be aggregated into the database. I have specific criteria to determine whether a document from the input already exists i ...

Reconfigure an ancestral item into a designated key

I have a single object with an array of roles inside, and I need to transform the roles into an array of objects. See example below: Current Object: displayConfiguration: { widgetList: { widgetName: 'widget title', entityType: 'As ...

Integrating Django templates with AngularJS

As I transition my website's front-end to Angular JS, the backend remains on Django. My original plan was to create a restful API for Angular to retrieve data from the backend. But it seems like generating partial templates in Django might be a simp ...

Can the issue of mangling be avoided during .NET minification?

Currently, I am utilizing the .NET Bundling and Minification feature to bundle and minify the files for my application. While this method works well, I am interested in exploring alternative solutions due to its complexity. Specifically, I am attempting t ...

The dynamic routing feature in React fails to function properly after the application is built or deployed

I'm facing an issue with getting a React route to function properly in the build version of my app or when deployed on Render. Here are the routes I have: <Route path="/" element={userID ? <Home /> : <Login />} /> <Route ...

Tips for correctly linking an Event Listener to the worldwide 'window' in Angular 6 and higher

Situation Within our Angular 6 application, an iframe is embedded to showcase third-party data. To facilitate secure cross-domain communication, the child iframe sends messages to the parent Angular app using window.postMessage() API. To receive these mes ...

Having trouble updating Django forms.py with the latest values from the database

models.py class Test(models.Model): name = models.CharField(max_length=256) slug_name = models.CharField(max_length=256) template = models.BooleanField("Is Template",default=False) @staticmethod def template_as_tuple(): return ...

The functionality of the button is affected when it is placed on the same line as a h1 heading

My goal is to have the page title and profile button aligned on the same line in the header of each page. However, I've encountered an issue where the button doesn't function properly when placed on the same line but works fine when separated ont ...

The Ajax request functions correctly in Chrome and Safari but encounters issues in Firefox and Internet Explorer

I've encountered an issue with jQuery where the call is failing when making a request with base64 authorization header in the beforeSend function. It's a simple request to retrieve projects. function GetProjects(full){ var query = "/Projects"; $ ...

Replace specific text with a span element around it?

I am working with the following HTML code: <p class="get">This is some content.</p>. My goal is to modify it so that it looks like this: <p class="get">This is <span>some</span> content.</p>. To achieve this, I have ...

Having difficulty getting a basic code to work: ajax method ($.post) with MySQL is not

I am facing an issue with this code not functioning properly. I want to display the result of a MySQL query without sending any data using my simple Ajax code. $('.myClass').on('click',function(){ $.post('resultAll.php'); ...

Just a Quick Query About Regular Expressions

I need help removing a specific part from a URL string, which looks like this: http://.....?page=1. I am aware that the code "document.URL.replace("?page=[0-9]", "")" does not work, so I am curious to learn how to accomplish this task correctly. Thank you ...

What is the reason behind only the final input value being shown on the screen?

I'm encountering an issue with my input fields. I have a total of five input fields. After filling all of them and clicking the button to display them on the screen, only the last one I entered is shown in all places... (let me know if this explanatio ...

Is it possible to pass an external function to the RxJs subscribe function?

Upon examining the RxJS subscribe method, I noticed that: subscribe(next?: (value: T) => void, error?: (error: any) => void, complete?: () => void): Subscription; So, I decided to create an example initialization function like this: private ...

Sidebar-driven top navigation menu

I am currently developing a Single Page Application using VueJS along with vuerouter. In my App.vue file, the structure is as follows: <template> <div id="app"> <header><topbar></topbar></header> <div cl ...

Ways to invoke a JavaScript function via a hyperlink. Various techniques to achieve this task

I want to create a div with the id of slider, and I am looking for a way to animate or hide it when a link is clicked. Specifically, I would like to toggle it open and close using a link. Javascript solution <script type="text/javascript"> ...

The Express application seems to load forever after a certain period of time

I encountered a peculiar problem with my express application. It was deployed on the server and functioning properly, but after a few hours, when I tried to access the website again, it kept loading indefinitely. Below is my app.js code: const express = r ...

Avoiding cheating in a JavaScript game

I am in the process of creating a JavaScript/JQuery game that resembles a classic brick breaker. The game includes features such as scoring, levels, and more. I have plans to add a leaderboard where users can submit their final scores. However, my concer ...

The reason for setting a variable as void 0 in JavaScript

Currently, I am delving into the libraries referenced in this particular article as well as other sources. There are some truly mind-boggling concepts contained within these resources, one of which is highlighted by the following line: var cb = void 0; I ...

Using a Function as an Argument to Return an Unnamed Object

There seems to be a common trend in JavaScript code where a function is passed as a parameter, which in turn returns an anonymous object. myFunction(function() { return { foo: 'bar' }; }); What benefits or reasons are there for u ...