The show/hide feature is malfunctioning

I need help with my PHP page where I display multiple choice questions from a database along with options and answers. Currently, I am using an HTML button to show/hide the answers but it only works for the first question. When I click on other questions, it still shows the answer for the first question. Can anyone assist me with this issue?

<script>
function toggleAnswer() {
  var x = document.getElementById('myDIV');
  if (x.style.display === 'none') {
      x.style.display = 'block';
  } else {
      x.style.display = 'none';
  }
}
</script>

<?php
while($row = mysqli_fetch_array($result)) {
    echo "<h4 style=font-weight:bold; text-align:justify>";
    echo "Q $row[slno]) $row[question]";
    echo "</h4><br>";
    echo "<ul class=list-group>";
    echo "<li class=list-group-item>1) $row[option1]</li>";
    echo "<li class=list-group-item>2) $row[option2]</li>";
    echo "<li class=list-group-item>3) $row[option3]</li>";
    echo "<li class=list-group-item>4) $row[option4]</li>";
    echo "<li class=list-group-item>5) $row[option5]</li>";
    echo "<div id=myDIV style=display:none><li class=list-group-item><b>Correct Option : ($row[correct_option])</b></div></li>";
    echo "<li class=list-group-item><button onclick=toggleAnswer()>View Answer</button></li>";
    echo "</ul>";
    echo "<hr color=#FF0000 size=5 width=100%>";
}
?>

Would appreciate any suggestions...

Answer №1

Give this a try:

 <script>
    function toggleAnswer(num) {
    var answer = document.getElementById('answer'+num);
    if (answer.style.display === 'none') {
        answer.style.display = 'block';
    } else {
        answer.style.display = 'none';
    }
    }
    </script>


<?php
  $number=1;
        while($row = mysqli_fetch_array($result))
        {
            echo "<h4 style=font-weight:bold; text-align:justify>";
            echo "Question $row[slno]) $row[question]";
            echo "</h4><br>";
            echo "<ul class=list-group>";
            echo "<li class=list-group-item>1) $row[option1]</li>";
            echo "<li class=list-group-item>2) $row[option2]</li>";
            echo "<li class=list-group-item>3) $row[option3]</li>";
            echo "<li class=list-group-item>4) $row[option4]</li>";
            echo "<li class=list-group-item>5) $row[option5]</li>";
            echo "<div id=answer".$number." style=display:none><li class=list-group-item><b>Correct Answer : ($row[correct_option])</b></div></li>";
            echo "<li class=list-group-item><button onclick=toggleAnswer('".$number."')>View Answer</button></li>";
            echo "</ul>";
            echo "<hr color=#FF0000 size=5 width=100%>";
          $number++;
        }

    ?>

Answer №2

Check out this solution:

Make sure that each Id is unique for every record.

<script>
function myFunction(elem) {
var x = document.getElementById('myDIV'+elem);
if (x.style.display === 'none') {
    x.style.display = 'block';
} else {
    x.style.display = 'none';
}
}
</script>


<?php

    while($row = mysqli_fetch_array($result))
    {
        echo "<h4 style=font-weight:bold; text-align:justify>";
        echo "Q $row[slno]) $row[question]";
        echo "</h4><br>";
        echo "<ul class=list-group>";
        echo "<li class=list-group-item>1) $row[option1]</li>";
        echo "<li class=list-group-item>2) $row[option2]</li>";
        echo "<li class=list-group-item>3) $row[option3]</li>";
        echo "<li class=list-group-item>4) $row[option4]</li>";
        echo "<li class=list-group-item>5) $row[option5]</li>";
        echo "<div id=myDIV'".$row['slno']."' style=display:none><li class=list-group-item><b>Correct Option : ($row[correct_option])</b></div></li>";
        echo "<li class=list-group-item><button onclick=myFunction('".$row['slno']."')>View Answer</button></li>";
        echo "</ul>";
        echo "<hr color=#FF0000 size=5 width=100%>";
    }
?>

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

Tips for eliminating repetitive code in JavaScript

I have a jQuery function that deals with elements containing a prefix 'receive' in their class or ID names. Now, I need to duplicate this function for elements with the prefix 'send'. Currently, it looks like this: function onSelectAddr ...

Resolving the problem with highlighting borders

I am facing an issue with 2 inputs displayed side by side as shown below: .centered-query-cn { height: 150px; display: flex; } .browse-query { display: flex; } .browse-query input { display: flex; flex-grow: 1 !important; } <link href="ht ...

What is causing the divs to not stretch across the entire width of the parent div?

Interactive Code Example: Snippet: <div style="width: 100%; overflow: hidden; height: 65px; background: #00CC00;"> <div style="width: 60%; overflow: hidden; float: left; background: #3074A3; color: #EDEDED; height: 65px; text-align: center; ...

Create a PHPMailer contact form that displays a confirmation message upon submission, all without using any PHP code within the

I successfully implemented a contact form using phpmailer, but I now need to completely separate the PHP and HTML code. This is necessary because I want the contact form to be included as a section in an index.html webpage, meaning it should be in .html fo ...

Adjust the width of the mosaic layout to a 50% / 50% ratio

I'm looking to adjust the layout so that each image occupies 50% of the page. Currently, one large image takes up 2/3 of the space and two smaller images take up the remaining 1/3. You can find the images here: To make the large image occupy 50%, yo ...

The image fails to appear

Check out my website at www.wostokhr.pl I am having trouble getting the picture "pics/hero.jpg" to show up in the "div id="hero"" section with a JS parallax function. I have double-checked the HTML and CSS validators and everything seems to be correct. An ...

Preventing Servlet Redirection in HTML: A Step-by-Step Guide

Is there a way to send data from an HTML web page to a server using a servlet without redirecting? <form method="post" name="customerForum" action="addCustomer"> <button class="btn btn-success" id="ad ...

When clicking, the fixed header and footer suddenly shift out of place

In my jquery mobile application, I am facing an issue with a fixed header and footer. Whenever I click on the screen, the fixed header and footer get displaced and are no longer fixed. I am unsure how to resolve this bug. Any suggestions on how to fix it w ...

Vue JS encounters difficulties when attempting to lazy load various images from a randomized image URL

I've implemented a code snippet for lazy loading images with different URLs: <img src="https://source.unsplash.com/1600x900/?hotel,booking.com?v=1" loading="lazy" /> <img src="https://source.unsplash.com/1600x900/?hot ...

ExternalInterface.call in as3 leading to crashes in web browsers

I have a webpage with HTML and JavaScript that successfully hides and displays a flash movie object. However, I encounter a problem when trying to exit from the tab - the browser crashes without any error message. Can anyone provide assistance? Thank you. ...

Select2 functions properly on online coding platforms like Fiddle but encounters issues when running on

I decided to incorporate Select2 (Source: ) for the purpose of selecting and tagging. After studying an example on JsFiddle I attempted to reproduce it on my local server (xampp). Below is the code, mirroring that of the fiddle. <!doctype html> &l ...

Adding plain HTML using jQuery can be done using the `.after()` and `.before()` methods

I have encountered a situation where I need to insert closing tags before an HTML element and then reopen it with the proper tags. The code snippet I am using is as follows: tag.before("</div></div>"); and then re-open it by adding proper tag ...

Create a grid layout of Bootstrap Cards using ReactJS

Looking to dynamically render Bootstrap cards based on the number of players. When there are 4 players, they should be displayed in a single column. However, when there are 5 or more players, I want the cards to spread out into two columns. What would be ...

Sometimes, checking a checkbox will trigger a cascading effect on other checkboxes

I have implemented 5 checkboxes in a vertical layout, each created using SVG and Polyline elements. The toggling functionality works fine when clicking on the label of each checkbox. However, sometimes clicking on the checkbox image toggles the wrong box! ...

Guide on integrating React.js into an HTML development webpage

I can't seem to get this code to work properly. I have saved it as an .html file on my computer, but it's not displaying anything when I try to open it in Google Chrome. <DOCTYPE! html> <html> <head> <script src= ...

IE throws an exception when attempting to use Canvas as it is not supported

One of my challenges involves working with a Canvas Element: <canvas id="canvas" width="300" height="300"> Sorry, your browser does not support the Canvas element </canvas> In my JavaScript file, I have the following code: var ct= docum ...

I encountered a problem in my Angular form where the keycode event for F2 is not functioning properly in certain scenarios. Can anyone help me diagnose the issue

During my Angular project, I created an HTML page with a form that includes input data with autofocus. To enhance user experience, I added an event listener for the "F2" key that triggers a console message. My objective is to ensure this functionality wor ...

Ways to update list item text with jQuery

I am attempting to create a button that can replace the content of a list item. Although I have looked at other solutions, I keep encountering this error message: Uncaught TypeError: Object li#element2 has no method 'replaceWith' I have experime ...

What is the best way to configure custom CSS styles in a React project?

I've been trying to position my Grid component from Material-UI, but so far, I haven't had any luck. What could be the issue here? class Scene extends React.Component { render() { const mystyle = { backgroundColor: "DodgerBlue", ...

Creating a bar chart with multiple rows using Morris.js

I am currently involved in a project and I have included the code below to generate a bar chart. In my database table called "bar," there are attributes such as id, factor, score, goal_1, goal_2, and goal_3. While I am not encountering any errors, unfort ...