I am having difficulty toggling text within a for loop in JavaScript

When I display a list of cards using a for loop and click on them, I want to toggle some text. The issue I'm facing is that it works fine for the top card, but when I click on the card below, it toggles the text of the first card instead. This is despite giving each card a different ID in the JavaScript toggle function.

Does anyone have any suggestions on what I might be doing wrong?

<!-- HTML -->
        {% for card in cards %}
                  <div class="card mb-3">
                    <div class="card-header">
                      <img class = "float:left mr-2 mt-1 small-profile-picture" src ="{{ card.creator.profile.image.url }}" >
                      <a class="mb-4 float-up"  > {{ card.creator }}</a>
                       <small> <p class=mt-2> {{ card.date }}  </p> </small>
        
                    </div> <!-- Card Header ender  -->
        
                    <!-- Here we have the questions and answers -->
                    <div onclick="myFunction()" style="cursor: pointer;">
                      <div class="card-body mt-4">
                        <h5 class="card-title"> <a class="article-title">{{ card.question }}</a></h5>
                        <p id="myDIV{{card.card_id}}"> Click to see Answer </p>
                        <!-- <p class="card-text"> {{ card.answer}} </p> -->
                      </div> <!-- Card body ender -->
                    </div>
    
<!--Javascript -->
              <script type="text/javascript">
                function myFunction() {
                    var x = document.getElementById("myDIV{{card.card_id}}");
                    if (x.innerHTML === "Click to see Answer") {
                      x.innerHTML = "{{card.answer}}";
                    } else {
                      x.innerHTML = "Click to see Answer";
                    }
                  }
    
              </script>
{% endfor %}

Appreciate you taking the time to read this

Answer №1

After careful consideration, there are several tweaks I would make to enhance this code. To maintain the integrity of your original code, I recommend the following adjustments: Firstly, extract the <script> tag from inside the loop to prevent redundant function redefinition with each iteration.

Secondly, separate the JavaScript logic and pass arguments to the myFunction instead of hardcoding strings within it for better flexibility.

Although unverified, these alterations should steer you in the right direction:

<script type="text/javascript">
    function myFunction(id, answer) {
         // Utilize template literal syntax below instead of Django handlebars.
        let x = document.getElementById(`card-${id}`);
        if (x.innerHTML === "Click to see Answer") {
            x.innerHTML = answer;
        } else {
            x.innerHTML = "Click to see Answer";
        }
    }
</script>

{% for card in cards %}
<div class="card mb-3">
    <div class="card-header">
        <img class = "float:left mr-2 mt-1 small-profile-picture" src="{{ card.creator.profile.image.url }}" >
        <a class="mb-4 float-up"> {{ card.creator }}</a>
        <small> <p class=mt-2> {{ card.date }}  </p> </small>
    </div>

    <div onclick="myFunction({{ card.card_id }}, {{ card.answer }})" style="cursor: pointer;">
        <div class="card-body mt-4">
        <h5 class="card-title"> <a class="article-title">{{ card.question }}</a></h5>
        <p id="card-{{ card.card_id }}"> Click to see Answer </p>
        </div>
    </div>
</div>
{% endfor %}

Answer №2

I made some modifications to the questions and answers section:

function updateContent(element) {
    element.querySelector('.card-body.mt-4 .card-text').classList.toggle('d-none');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="abdbc4dbdbced985c1d8eb9a859a9a9d859b">[email protected]</a>/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>

<div onclick="updateContent(this)" style="cursor: pointer;">
    <div class="card-body mt-4">
        <h5 class="card-title"> <a class="article-title">{{ card.question }}</a></h5>
        <p id="useless...."> Click here for Answer </p>
        <!---   removed comment from the next line -->
        <p class="card-text d-none"> Here is the solution ....{{ card.answer}} </p>
    </div> <!-- End of Card body -->
</div>

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

Can I use a single component for all routes in NextJS?

Just starting out with NextJS and facing a simple problem: I'm wondering if it's possible to achieve the following setup using NextJS // with react-router-dom <Router> <> <Header /> <Switch> & ...

Is Jade monitoring *.jade files?

Though I am not sure of the internal workings of Jade, my best guess is that it compiles each template file once and then employs a compiled and cached version for subsequent HTTP requests. One intriguing observation I have made while running my Express a ...

Creating an X pattern on an HTML5 canvas and detecting intersections with a perimeter

I am currently developing a maze game using HTML 5. Below is the function I have implemented to draw an "X" on the canvas (the player will guide the X through the maze using touchpad). dim = 8; function rect(x,y,xdim){ ctx.beginPath(); ctx.moveT ...

The issue with mediaDevices.getUserMedia not functioning properly in Safari 11 on iOS 11 persists, as the video output appears as a

I'm having trouble understanding why my code is not working. I've read that Safari 11 should be compatible with getUserMedia APIs from iOS 11, but for some reason it's not functioning as expected. My aim is to capture a QR code in a live str ...

Executing multiple jQuery Ajax requests with promises

I've been learning how to use promises gradually, and now I'm faced with the challenge of handling multiple promises. In my code snippet, I have two email inputs in a form that both create promises. These promises need to be processed before the ...

Button click functionality for updating in Classic ASP is functioning correctly exclusively in Internet Explorer and not in other web browsers

Currently, I am in the process of enhancing a Classic ASP application. Within this application, there is an HTML table that is populated from a SQL database. One cell within the table contains checkboxes. Upon clicking one of these checkboxes, a popup wind ...

What is the best way to have text wrap around an icon in my React application?

I am facing an issue while trying to display the note description over the trash icon in a React app. I have tried various methods but can't seem to achieve the desired effect. Can anyone guide me on how to get this layout? Here is what I intend to a ...

Sending a variable using the onchange function in jQuery

I have written a script to toggle the visibility of different divs based on selection var folder; $(function() { $('#teamleag').change(function() { if ($('#teamleag').val() == 'footballal') { $('# ...

Is there a way to determine whether a mouse-down event took place on the scroll-bar or elsewhere within the element?

Looking for a solution with my HTML div acting as a canvas containing various objects. The issue lies in the fact that when attempting to draw a selection rectangle by dragging with the mouse, if scroll bars appear due to the large size of the canvas, scr ...

Ways to decrease font size and insert a line break within a constrained input space?

I am facing an issue where the input box remains static with old numbers when it overflows, and newly typed numbers do not appear at all. <!DOCTYPE html> <html> <body> <input type="text" id="output-area" placehold ...

Issue with Angular translation when utilizing a dynamic key variable

I am currently developing a project with Angular Js and incorporating the Angular-translate module In a specific scenario, I encountered an issue where the translation key needed to be stored as a variable. To address this, I created an object within the ...

The URL in a request is altered prior to execution

I am encountering an issue with my NodeJS application where it automatically appends my domain to the URL set in my http request. How can I prevent this from happening? I have tried to search for similar problems but have not found any relevant solutions. ...

Tips for uploading files in asp.net using an ajax call

I have developed a small asp.net web forms application for managing emails. The interface allows users to input mandatory information such as sender, recipient, and subject. I am now looking to implement file attachments in the emails using the asp.net fil ...

Guide on how to iterate through the list of users within the component

Hello, I'm fairly new to working with react and I've encountered a challenge regarding implementing a loop within this component to display a list of all users. Despite trying numerous approaches, I haven't been able to figure it out. colum ...

Fade-in animation of a clock on an SVG image

I am trying to achieve a unique fade-in effect for an SVG image in my HTML. The challenge is to make the fade-in start from the top of the image and progress in a circular motion until it completes a full circle. An example of the effect I am aiming for is ...

Disabling Javascript in Chrome (-headless) with the help of PHP Webdriver

I am experimenting with using Chrome without JavaScript enabled. I attempted to disable JavaScript by adding the --disable-javascript command line argument. I also tried some experimental options: $options->setExperimentalOption('prefs&a ...

Adjust the size of items using a background image that covers the element

I'm struggling with a seemingly simple task here. I've been experimenting with different methods, but I just can't seem to grasp it. On the front page of my website, there is a cover section that contains a logo and a button: <section i ...

Can a file object be transmitted using this method?

I'm new to jquery and I am attempting to upload a File object obtained from my HTML: <label for="photo" class="col-xs-2">Photo</label> <input id="photo" name="fileName" type="file" class="col-xs-4"/> This is the snippet of my J ...

Creating automatic page additions using Node.js on Heroku?

Can you assist me with a challenge I'm facing? Currently, I am using node.js and heroku to deploy an application and each time I add a new post, I have to manually update my web.js file. This process was manageable when I had fewer pages, but now it&a ...

I am having trouble displaying SASS styles in the browser after running webpack with node

In my current project for an online course, I am utilizing sass to style everything. The compilation process completes successfully without any errors, but unfortunately, the browser does not display any of the styles. The styles folder contains five file ...