Using JavaScript within a Django Template

My JavaScript code inside a Django template is not responding. What should I do?

This is what's within the <script> tag:

var pageStrucVal = {{ pagestruc }};
        if (pageStrucVal >= 82){
            var pageWarn = ["Brilliant, your site's structure and design is awesome and rocking. <gold>RockingStructure</gold>", 'pp']
        }
            
        else if ( pageStrucVal >= 72){
            var pageWarn = ["Nice, your site's structure and design is suitable", 'pp']
            }
        
        //other conditions...
        
        console.log(pageWarn);
        document.getElementById(pageWarn[1]).appendChild(document.createElement('p')).innerHTML = (pageWarn[0]);
    

Is

document.getElementById(pageWarn[1]).appendChild(document.createElement('p')).innerHTML = (pageWarn[0]);
written correctly and in the right place?

Here's a snippet of the HTML:

<div class='plusNdefects' id='moredetails'>
            <h1>Good Aspects and Plus Points.</h1>
            <p class='details'>Here are some awesome good aspects...</p>
        
            //more HTML code...
        </div>
        
        <div class='plusNdefects'>
            <h1>Disabilities and Improvements.</h1>
            <p class='details'>These are some disabilities...</p>
            
            //more HTML code...
        </div>

'pp' and 'dd' represent the IDs where I intend to display the messages - 'pp' for plus points and 'dd' for defects.

Answer №1

In my opinion, incorporating user quotes outside of the Django tag is a more efficient approach.

var pageStructureValue = parseInt('{{ pagestruc }}');

Answer №2

experiment with

let pageStructureValue = parseInt({{ pagestruc }})
;

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

Utilizing dynamic IDs in JavaScript for HTML elements: A comprehensive guide

I am in the process of dynamically creating a drop-down box. While I have successfully created dynamic drop-down boxes, I now need to populate them with values from a database. To achieve this, I believe I need to use an on-click function. Despite attemp ...

Using the <script> attribute within the <head> tag without the async or defer attributes

https://i.stack.imgur.com/cRFaR.pngCurious about Reddit's use of the async or defer attribute in the script tag. Are there situations where blocking the parser is necessary? ...

The function $.fn.dataTable.render.moment does not exist in npm package

I have encountered an issue with my application that I am struggling to solve: I want to format dates in my data table using Moment.js like I have done in the following script: $().ready(function() { const FROM_PATTERN = 'YYYY-MM-DD HH:mm:ss.SSS&a ...

Converting JavaScript TimeStamp to MilliSeconds

How can I convert a timestamp like 09-MAR-11 04.52.43.246000000 AM to milliseconds using JavaScript? I need to achieve this conversion within JavaScript only. Any help would be greatly appreciated. Thank you. ...

Using ng-model with ng-repeat element

There is a situation where I need to replicate the <li> item and incorporate a dynamic model for writing click events. <ul class="flights trip1-list" ig-init="trip1_fare = 0"> <li ng-repeat="data in flt_det" ng-click="addUp($event)" ng ...

"Troubleshooting: show() Function Not Functioning Properly

Though this may seem like a straightforward piece of code, I've hit a snag somewhere along the way. It's just evading my grasp. #div { display:none; } JS: function show() { var className = 1; $("#div." + className).show("slow") ...

Exploring the concept of SOCKET.IO with rx.js in an Angular application

I am currently working on an Angular (2) application and I need to ensure that the view is updated whenever there is a change in the data from the back end. getData() { return this.http.get("some url") .map(result => result.json()); } ...

Routing in Express - Direct users based on their chosen language

I have been working on setting up routing for my multilingual website with the intention of redirecting users based on their detected language. Here is a snippet of the code I currently have: app.get('/(:lang)?', (req, res, next) => { co ...

Using icontains with PostgreSQL in Django ORM can sometimes lead to inaccurate data being returned

Here is my model: class Supplier(models.Model): supplierId = models.IntegerField('Supplier ID', primary_key=True) supplierName = models.CharField('Поставщик', max_length=255, null=True, blank=True) inn = models.Char ...

The registration process is not functioning

After creating the RegistrationForm and necessary views, I am facing an issue where nothing happens when I try to register. After filling out the form and clicking "register," the site simply refreshes and shows a blank form again. Any ideas on what could ...

what is the best approach to incorporate this condition into a Django template

Can you help me with implementing a condition in a Django template using multiple "and" or "or" statements within an if statement? {% if ((email_setting.twitter_link is not None and email_setting.twitter_link != '') or (email_setting.instagram ...

Pairs of values in dynamic arrays: Assigning values to the first element and second element

Encountering errors stating "subscript requires array or pointer type" while dealing with an array of pairs. Despite researching similar issues faced by others, I have not been successful in resolving it. I constructed an array of pairs dynamically as sho ...

Trouble with the onload function in onMounted vue3

For my vue3 component, I need to load certain scripts. Here is what I am currently implementing: <script setup> import { onMounted } from 'vue' function createElement (el, url, type) { const script = document.createElement(el) if (type ...

Distinct elements within a JavaScript hash

Is there a jQuery method to add a hash into an array only if it is not already present? var someArray = [ {field_1 : "someValue_1", field_2 : "someValue_2"}, {field_1 : "someValue_3", field_2 : "someValue_4"}, {field_1 : "someValue ...

What could be causing my CORS fetch request to not send cookies to the server?

Trying to work out a CORS request using the fetch method: fetch('https://foobar.com/auth', { method: 'GET', mode: 'cors', credentials: 'include', }) The server-side code in express for impl ...

Django: One database serving multiple applications

I am looking to centralize my models.py file for multiple applications in Django. I want the database tables to be created from this centralized models.py using manage.py. Currently, my Django 1.4 standard directory structure looks like this: myproject ...

Permission denied: Node.js bash was trying to access /usr/local/bin/node, but was unable

I've been working on setting up Node.js on my Ubuntu machine. I carefully followed the step-by-step instructions provided by the official documentation: ./configure && make && sudo make install After following the steps, I was able t ...

The componentDidMount event of the child component is throwing an error due to the parent state being

I'm experiencing an issue where the value passed from the parent component to the child component via props is showing as undefined when logging it in the componentDidMount event of the child component. I need this value to be properly updated and acc ...

Creating interactive buttons with CSS and jQuery

As a newcomer to coding, I'm trying my hand at creating two buttons that transition from green to blue with a single click, and eventually incorporating them into a live website. The functionality I'm aiming for includes: Both buttons startin ...

How can you implement code that responds differently based on whether the user clicks the OK, cancel, or close button in a confirm dialog

What are three buttons in a confirm dialog box? How can JavaScript be used to perform different actions when the "ok" and "cancel" buttons are clicked, without performing any action when the dialog box is closed? ...