What is the best way to toggle the visibility of the answers to a question when the corresponding hyperlink is clicked, and how can the text on this hyperlink be updated dynamically using jQuery?

I am currently working on a website using PHP, Smarty, and jQuery. On this website, I have a page that features a list of questions along with their available answer options and the correct answer. This page is dynamically generated using the "Smarty Template Engine" and can contain one or multiple questions. For demonstration purposes, I am displaying only two questions here. The goal is to create a functionality where all answer options for each question are hidden when the page loads, and a hyperlink labeled "Show Answers" is displayed. Upon clicking on the "Show Answers" link for a specific question, the available answer options and correct answer should be revealed, and the title of the hyperlink should change to "Hide Answers". Clicking on "Hide Answers" should hide the answers again. I am looking to achieve the same functionality demonstrated in the following jsFiddle example: You can find the reference fiddle here. If anyone knows how to implement this using jQuery, I would greatly appreciate your help. Thank you for taking the time to understand my issue. I look forward to seeing your solutions. Here is a link to my non-working jSFiddle: http://jsfiddle.net/LbVFc/ Below is the HTML code for the two questions and their answers (same as in the provided jsFiddle):

<div id="body">
    <div class="container-fluid" style="padding-bottom: 50px;">
        <div class="row-fluid">
            <div class="col-sm-12" style="max-width: 768px; margin: 0 auto; margin-top: 10px; padding: 8px;">
                <div style="width: 100%; margin: 0 auto; overflow: hidden; color: #381D6E; padding-bottom: 10px;">
                  //HTML content repeated as-is...
                </div>
            </div>
        </div>
    </div>
</div>

Answer №1

Check Out This Code

  • Add a class opt to OPTIONS div and Answers div
  • You Can Utilize this HTML Markup And JavaScript

    HTML
    
    <div id="body">
        <div class="container-fluid" style="padding-bottom: 50px;">
            <div class="row-fluid">
                <div class="col-sm-12" style="max-width: 768px; margin: 0 auto; margin-top: 10px; padding: 8px;">
                    <div style="width: 100%; margin: 0 auto; overflow: hidden; color: #381D6E; padding-bottom: 10px;">
                        <ul style="padding: 0;">
                            <li>
                              <div class="list-div">
                                <div style="font-weight: 700; font-size: small; float: right; margin-right: 5px; margin-top: 2px;"><a href="#" class="fav_que" id="66602">Remove From Favourite Question</a></div>
                                <div style="text-align: left;">                                 
                                    Question 1.
                                    </div>                          
                                    <div style="text-transform: uppercase; font-weight: 700; float: left; margin-right: 1%; width: 24%; min-width: 95px;">DIRECTION:</div>
                        <div style="width: 74%; float: left;"><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"></div>
                                    <br/>
                                    Question :<br/><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
                                    <html><body><p>Current versus time and voltage versus time graph of a circuit element is shown below :<img src="http://www.entranceprime.com/upload_media/questions/original/1330939560_49.jpg"><img height="68" src="http://www.entranceprime.com/upload_media/questions/original/1330939630_49.1.jpg" width="117"></p></body></html>
                    <div style="width: 100%; overflow: hidden; margin-bottom: 4px; margin-top: 4px;">
                                        <div style="font-weight: 700; font-size: small; float: right; margin-right: 5px;">QUE66602</div>
                                    </div>
                    <a href="#" style="color:#3F368B; text-decoration: underline;" class="show-ans">Show Answers</a>
                  </div>
                  <div class="list-div">
                    <div class='opt' style="text-transform: uppercase; font-weight: 700; float: left; margin-right: 1%; width: 24%; min-width: 95px;">Options:</div>
                        <div class='opt' style="width: 100%; margin-top: 8px;">
                                        <label class="radio-section" for="radio_1">
                                          <div class="radio-select">1)</div>
                                            <div class="radio-div">
                                                capacitance of 2 F
                              </div>
                                        </label>
                                        <label class="radio-section" for="radio_2">
                                            <div class="radio-select">2)</div>
                                            <div class="radio-div">
                                                capacitance of 1 F
                              </div>
                                        </label>
                                        <label class="radio-section" for="radio_3">
                                            <div class="radio-select">3)</div>
                                            <div class="radio-div">
                                                a voltage souice of emf 1V
                              </div>
                                        </label>
                                        <label class="radio-section" for="radio_4">
                                            <div class="radio-select">4)</div>
                                            <div class="radio-div">
                                                <img src="http://localhost/eprime/epmobile/web/ckeditor_3.6.1/plugins/ckeditor_wiris/integration/showimage.php?formula=2d685d462cd3331c46f7fac8ca3e1f6a.png" class="Wirisformula" align="middle">
                              </div>
                                        </label>
                                        <label class="radio-section" for="radio_2">
                                            <div style="text-align: left;"><b>Correct Answer :</b>2</div>
                                        </label>            
                                    </div>
                                </div>
                            </li>   
                        <li>
                              <div class="list-div">
                                <div style="font-weight: 700; font-size: small; float: right; margin-right: 5px; margin-top: 2px;"><a href="#" class="fav_que" id="80763">Remove From Favourite Question</a></div>
                                <div style="text-align: left;">                                 
                                    Question 2.
                                    </div>                          
                                    <div style="text-transform: uppercase; font-weight: 700; float: left; margin-right: 1%; width: 24%; min-width: 95px;">DIRECTION:</div>
                        <div style="width: 74%; float: left;"><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"></div>
                                    <br/>
                                    Question :<br/><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
                                    <html><body><p>Derive the expression for the time period of a simple pendulum which depends on the lenght, mass, and gravitational acceleration.</p></body></html>
                    <div style="width: 100%; overflow: hidden; margin-bottom: 4px; margin-top: 4px;">
                                        <div style="font-weight: 700; font-size: small; float: right; margin-right: 5px;">QUE80763</div>
                                    </div>
                    <a href="#" style="color:#3F368B; text-decoration: underline;" class="show-ans">Show Answers</a>
                  </div>
                  <div class="list-div">
                    <div class='opt' style="text-transform: uppercase; font-weight: 700; float: left; margin-right: 1%; width: 24%; min-width: 95px;">Options:</div>
                        <div class='opt' style="width: 100%; margin-top: 8px;">
                                        <label class="radio-section" for="radio_1">
                                            <div class="radio-select">1)</div>
                                            <div class="radio-div">                    
                                                <img src="http://localhost/eprime/epmobile/web/ckeditor_3.6.1/plugins/ckeditor_wiris/integration/showimage.php?formula=b8bb97da575d595129425d5ba0cac48e.png" class="Wirisformula" align="middle">
                              </div>
                                        </label>
                                        <label class="radio-section" for="radio_2">
                                            <div class="radio-select">2)</div>
                                            <div class="radio-div">                    
                                                <img src="http://localhost/eprime/epmobile/web/ckeditor_3.6.1/plugins/ckeditor_wiris/integration/showimage.php?formula=2fa6f58b13fc7b4dbb999484c01320ca.png" class="Wirisformula" align="middle">
                              </div>
                                        </label>
                                        <label class="radio-section" for="radio_3">
                                            <div class="radio-select">3)</div>
                                            <div class="radio-div">                    
                                                <img src="http://localhost/eprime/epmobile/web/ckeditor_3.6.1/plugins/ckeditor_wiris/integration/showimage.php?formula=18d2b494bf784790e26d743900503669.png" class="Wirisformula" align="middle">
                              </div>
                                        </label>
                                        <label class="radio-section" for="radio_4">
                                            <div class="radio-select">4)</div>
                                            <div class="radio-div">                    
                                                <img src="http://localhost/eprime/epmobile/web/ckeditor_3.6.1/plugins/ckeditor_wiris/integration/showimage.php?formula=4e3da7281a68c57642beb71a7fddd9d6.png" class="Wirisformula" align="middle">
                              </div>
                                        </label>
                                        <label class="radio-section" for="radio_2">
                                            <div style="text-align: left;"><b>Correct Answer :</b>1</div>
                                        </label>            
                                    </div>
                                </div>
                            </li>           
              </ul>                                     
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    
    JavaScript
    
    $(document).ready(function () {
    
    $('.opt').hide();
    
            $('a.show-ans').click(function (e) {
                $(this).parent().next().find('div.opt').toggle();
                if ($(this).text() == "Show Answers") {
                    $(this).text('Hide Answers')
                }
                else {
                    $(this).text('Show Answers')
                }
                e.preventDefault();
            });
    
    });
    

    VIEW THE DEMO HERE

    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

    Locating the jQuery element just one element next to it

    Having set up my HTML like this. <div id="wrap"> <div class="left"></div> <div class="right"> <a href="#">link</a> </div> <div class="listings" style="display:none"> <ul> ...

    Utilize JQuery to extract data from JSON and populate form inputs

    Working on a web project where I need to make use of AJAX and JQuery to update certain fields without refreshing the entire page. After testing, everything seemed to work fine with dummy data. However, when trying to parse actual JSON data generated from M ...

    What is the best way to toggle the color of the circle div in the center between yellow and white with every click within the circle?

    Up to now, I have successfully accomplished this with just one click. I deleted the lightbulb image const sphere = document.getElementById("sphere"); sphere.addEventListener("click", event => { console.log("You clicked the ...

    The expected result is not obtained when making an Ajax request to a PHP variable

    I recently encountered an issue with my AJAX GET request. The response I received was unexpected as the PHP variable appeared to be empty. Here is the snippet of jQuery code that I used: jQuery(document).ready(function($) { $.ajax({ url: '/wp ...

    Which is more efficient for rendering performance: using images, CSS gradients, or box shadows with borders?

    I'm curious about improving website scroll and animation performance. Which option would be better for your mobile webapp or website: Using a repeating thin image or CSS3 gradient? or Utilizing a repeating image instead of box shadow with a borde ...

    JQuery Multiple Selection

    Can someone please explain how to execute a multi match in jQuery? For example, matching id = a + num + b + num or id = a + num + c + num (where num ranges from 1-99). Any assistance would be greatly appreciated. Thank you. if($(this).attr("id").match(/ ...

    How can I design a tooltip window using HTML, jQuery, or other elements to create a box-like effect?

    As someone who is new to front end development, I am facing a challenge with my web app. The requirement is that when a user hovers over an image, I need a 'box' to open nearby and display a pie chart. Although I have managed to get the hover fu ...

    Encountering issues with the transmission and retrieval of ajax data in Struts 2 framework

    Currently, I am attempting to transmit data through ajax and then retrieve the same using ajax. Below is the snippet of my ajax code: $.ajax({ url:"getSampleData", type:'GET', data : {'var':cellValue}, ...

    Determine the height of an image using JavaScript

    How can I retrieve the height of an image in a JavaScript function? When I use the code: var image_height = $(image).height(); The value of image_height is 0, even though my image definitely has non-zero height. Is there a different method to accurately ...

    Searching for answers for Pyramid and AJAX (Jquery) inquiries

    If I have a file named somefunction.py in my Pyramid package directory and I want to use $.post to call this function, what URL should I specify to invoke this function? Assuming I have a view function called aview defined in views.py, can I access this ...

    Utilizing window.matchMedia in Javascript to retain user selections during page transitions

    I am encountering difficulties with the prefers-color-scheme feature and the logic I am attempting to implement. Specifically, I have a toggle on my website that allows users to override their preferred color scheme (black or light mode). However, I am fac ...

    I am experiencing an issue wherein after using jquery's hover() function, the CSS :hover state is not

    Following the jquery hover function, the css hover feature ceases to work. In my html, there are multiple svg elements. A jquery script is applied where hovering over a button at the bottom triggers all svg elements to change color to yellow (#b8aa85). S ...

    Vanishing Submenus

    I'm experiencing an issue with my navbar and its drop-down menus. When I hover over the submenu, it doesn't stay visible as expected. I've tried different approaches such as using jQuery, the + operator in CSS, and even creating a separate h ...

    Using JQuery to Manipulate Checkboxes

    Recently, I've been facing an issue with JQuery and Checkboxes. Let me provide you with an example: <input type="checkbox" name="guest" value="1" /> <input type="checkbox" name="guest" value="2" /> <input type="checkbox" name="guest" v ...

    Preventing jQuery plugin from overriding default settings

    I have created a jQuery plugin using the nested namespace pattern, inspired by the design template found in Addy Osmani's book. The plugin is a simple gallery and everything seems to be functioning correctly. However, I am facing an issue when attemp ...

    Generating dynamic content in a text field based on user selection from a dropdown menu using PHP

    I have a database with two fields: package_title and package_cost. I am currently displaying the package_title in a dropdown menu using a while loop. When a customer selects a package_title from the dropdown, I would like to show the corresponding cost (pa ...

    There has been an issue with parsing the JSON file due to an invalid character found at

    I keep encountering a parse error whenever I attempt to send a post request to the server. $.post("../php/user_handler.php", formData, function(data) { var result = JSON.parse(data); if(result.status === 'error') { ...

    Using ajax to submit a request to the controller

    I'm currently developing an ASP.NET Core MVC application and have a registration page set up. My goal is to return View with errors if the model state is false: @model WebApplication2PROP.Entities.UserRegister @* For more information on enabling M ...

    ASP.Net Core Razor: Troubleshooting Null JSON Value in Ajax Requests

    I am currently using .Net Core Razor for my application and encountering an issue with passing values to the controller when calling the action from Ajax. Below is the script I am using: var table = $('#dataTable').DataTable(); var data = table. ...

    The utilization of CakePHP buttons for submitting forms, along with the seamless integration of

    <?php echo $this->Form->button('A Button'); echo $this->Form->button('Another Button', array('type'=>'button')); echo $this->Form->button('Reset the Form', array('type'=> ...