Issues with HTML rendering within a JavaScript function in Django

One of my Django templates includes a Javascript function. Here's an example:

<a class ="edit" href="{% url notecards.views.edit_notecard notecard.id %}"> Edit </a>
<h3 class="notecard"><p id="boldStuff">{{ notecard.notecard_name }}</p></h3>
<input id ="myButton" type="button" onclick="changeText()" value="View Answer"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script>
<script type="text/javascript">
function changeText(){
    if (document.getElementById("boldStuff").textContent == "{{ notecard.notecard_name }}")
      {
            document.getElementById("boldStuff").textContent = "{{ notecard.notecard_html|safe }}";
            $("#myButton").prop("value", "View Question");
      }
    else
      {
            document.getElementById("boldStuff").textContent = "{{ notecard.notecard_name }}";
            $("#myButton").prop("value", "View Answer");
      }
}
</script>

While this script functions correctly with regular variable values, it encounters issues when the values contain HTML. Clicking the button doesn't trigger any action. The console displays messages such as undetermined string literal and changeText is not defined.

Here's an excerpt from my page source that illustrates the problem with one of the values:

function changeText(){
    if (document.getElementById("boldStuff").textContent == "Here is a question hey whats up?")
      {
            document.getElementById("boldStuff").textContent = "<p>Here is an answer hey whats up. </p>
<p>Here is an answer hey whats up. Here is an answer hey whats up. </p>
<p>Here is an answer hey whats up.</p>
<p>Here is an answer hey whats up.Here is an answer hey whats up.vHere is an answer hey whats up. v</p>";
            $("#myButton").prop("value", "View Question");
      }
    else
      {
            document.getElementById("boldStuff").textContent = "Here is a question hey whats up?";
            $("#myButton").prop("value", "View Answer");
      }
}

The values can include paragraph tags, list items, and other HTML elements.

I have attempted using both .textContent and .innerHTML, but the issue persists.

Thank you

Answer №1

Implement the escapejs template filter

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 server encountered a "Cannot GET /socket.io" error while trying

I am experiencing an issue with my app that uses express/socket.io. The app is running smoothly without any errors, but when I make an http-request, I receive the following error message: GET http://xxxxxxx.com:3035/socket.io/1/?t=1449090610579 400 (Bad R ...

Adding middleware to the res.render() function can be extremely helpful when dealing with a large number

Recently, I put together a webpage for local use and it involves many routes. Specifically, I have 31 .ejs files and 3 .html files all neatly stored in the "views" folder. //app.js - using node and express app.get('/page1', function(req, res ...

Difficulty Converting Array of Objects to Proper Type with Q.Promise and KO.mapping

I have encountered an issue while trying to filter an observable array. It seems that the ko.utils.arrayFilter method is converting all my model's field names to lowercase, causing unexpected behavior. I should mention that this project involves Types ...

I am looking to showcase the information from two separate collections

I am looking to display data from two separate mongoose collections. I have a Member collection and a Property collection. Below is my code for fetching the data: const Property = require('../models/propsSchema') const Members = require(&apo ...

Guidelines for integrating registration and login functionalities as an API with ViewSet in Django Rest Framework over generic views

I am diving into the world of viewset while utilizing Django Rest Framework to develop registration and login functionalities as an API using ViewSet rather than generic views, and exposing resources to a React frontend app on a different port. In a previo ...

Is it possible to restrict the acceptance of certain variables from a CSV file in Django form fields, instead of accepting

In my Django model, I have two fields for latitude and longitude which are both declared as CharField. The model needs to accept multiple coordinates, so in the UI form, I enter these coordinates separated by commas. I then split this char input in a funct ...

Is it possible to disregard any spaces within the content of an <option> element?

In my current project, I am facing an issue where a Django server is sending JSON data to a template with Vue.js running on it. The problem arises from the fact that some values in the JSON data have trailing spaces, causing complications. I am looking for ...

Struggling with certain aspects while learning Nodejs and ES6 technologies

Below is an example of using the ES6 method.call() method that is causing an error var obj = { name: "Hello ES6 call", greet: function(somedata) { this.somedata = somedata console.log(this.somedata) ...

Determine the maximum and minimum numbers by inputting a number and utilizing jQuery

<script type="text/javascript"> function findLargestNumber() { var number1, number2; number1 = Number(document.getElementById("N").value); number2 = Number(document.getElementById("M").value); if (number1 > numb ...

Struggling with the django.core.exceptions.SuspiciousFileOperation error message when trying to join paths

When running "python manage.py collectstatic," I encountered an issue where it seems to not be working for any file, with fa-brands-400.eot being the first affected file. Error: I received the following error: django.core.exceptions.SuspiciousFileOperati ...

Conceal the parent div from its sibling within the same parent container

My goal is to conceal a parent component from its child element. I attempted to achieve this by using the parent component as a background while adding additional backgrounds to the child elements for overriding purposes. However, this method did not work ...

What are the steps to verify a query's accuracy and effectively manage any errors that may arise

When using my API, the endpoint '/api/students' will display all student names. If a req.query is input with a specific name, such as "John", the endpoint becomes '/api/students?name=John'. I have implemented regex to ensure that only c ...

The left-hand operator in Typescript is not valid

I am a beginner in typescript and I have been following a tutorial called Tour of Heroes on Angular's website. In the final chapter of the tutorial, when I tried to use HTTP with the provided code, everything seemed to run fine but I encountered an er ...

Is it possible for .getElementByClassName to identify Ajax.GET elements?

I've run into a problem that I need help with: The issue arises when I have an API that makes an Ajax GET request. In the success function, it creates a button, a div, and several span elements with information inside, each with its own class. The GE ...

Exploring the getServerSideProps function in Next.js with a loop

I'm currently diving into the world of Next.js and facing an issue while trying to retrieve data from the database and display it on the index page. The problem arises when I execute the getServerSideProps function, as it seems to enter into a loop an ...

Modifying the user interface (UI) through the storage of data in a class variable has proven to be

If I need to update my UI, I can directly pass the data like this: Using HTML Template <li *ngFor="let post of posts; let i = index;"> {{i+1}}) {{post.name}} <button (click)="editCategory(post)" class="btn btn-danger btn-sm">Edit</butto ...

Swapping an H1 element from one document with an H1 from another document can be accomplished using JQuery

As a student, I am seeking your patience as I navigate through this assignment. My professor assigned us the task of watching 5 YouTube videos and then challenged us to use JQuery for programming instead of standard JavaScript. All I aim to do is switch an ...

Transform a text hyperlink into an image by hovering over it

Is there a way to turn a text hyperlink into an image when hovered over? I've seen image rollovers, but I'm not sure how to code a text-to-image rollover. I'm unsure where to start and which programming language to use—JavaScript, PHP, o ...

What are your thoughts on this method for preventing scrolling?

Is there a way to prevent scrolling of the underlying content on a webpage when a modal is displayed? I found this code snippet that achieves that. (http://jsfiddle.net/77P2e/) var $window = $(window), previousScrollTop = 0, scrollLock = false; $window.s ...

Press the button to modify the titles of the table

One of the tasks I'm working on involves a table with column titles. In this table, there's an edit button that, when clicked, should convert the title into an input field with the current title as its initial value. The edit button will then cha ...