Navigating Through Radio Questions with a Back Button Using Javascript

Having trouble looping through an array of objects with 'back' and 'next' buttons? It seems that the loop is not functioning correctly. The aim is for the 'back' button to decrement based on the number of times the 'next' button is pressed.

Check out the function that controls the back button navigation through sets of radio questions. For the complete code, please visit my JS Fiddle. Thank you!

     var questions = {

    allQuestions: [


        {
            topQuestion: [" 1a) Click on which music producer, produced Justins Timberlake 4th Album?", "2a)Click on which famous celebrity did Justin Timberlake date in 1999? ", "3a)Click on which social media movie did Justin Timberlake starred in?", "4a)Click on what famous disney kids show did first Justin Timberlake made his first appearance?", "5a)Click on which famous singer did Justin Timberlake accidently tear clothes off during a performance?", "6a)What magazine named Justin Timberlake the Most Stylish Man In America?"],
            question: "1a)What popular site did Justin Timberlake invest 2.2 Million Dollars in? ",
            choices: ["Linkedin", "Facebook", "Myspace", "Youtube"],

        }, {
            question: "2b)Select which movie did Justin Timberlake film score in 2008?",
            choices: ["The Incredibles", "Shark Tank", "Finding Memo", "Star Wars"],
            correctAnswer: 1
        }, {

            question: "3b)What city was Justin Timberlake born in?",
            choices: ["Chicago", "Detroit", "Tenessee", "New York"],
            correctAnswer: 2
        }, {


]
};

      var newQues = Object.create(questions);

         var k = 0;
         var chngeRadio = 0;


         for (var i = 0; i < 4; i++) {


    container = document.getElementById("container");
    list = document.getElementById("list");
    var li = document.createElement("input");
    li.type = 'radio';
    li.name = 'radio_group';
    li.id = 'id1';
    li.value = newQues.allQuestions[i].correctAnswer;
    list.style.textAlign = "center";

    document.body.appendChild(li);
    div = document.createElement("div");
    text = document.createTextNode(newQues.allQuestions[0].choices[i]);
    list.appendChild(div);
    div.appendChild(li);
    div.appendChild(text);

}


     btn1.onclick = function (event) {
        event = EventUtil.getEvent(event);


        k++;

        while (list.firstChild) {
            list.removeChild(list.firstChild);
        };

         for (var m = 0; m < 4; m++) {


            container = document.getElementById("container");
            list = document.getElementById("list");
            var li = document.createElement("input");
            li.type = 'radio';
            li.name = 'radio_group';
            li.id = 'id1';
            li.value = newQues.allQuestions[m].correctAnswer;
            list.style.textAlign = "center";
            div = document.createElement("div");
            text = document.createTextNode(newQues.allQuestions[k].choices[m])
            //alert(k);
            list.appendChild(div);
            div.appendChild(li);
            div.appendChild(text);

        };



          // The event object is assigned to the back button, aiming to loop through the radio questions backward, but currently only decrements once
    if ( k >= 1) {

        btn2.onclick = function(event){
            event = EventUtil.getEvent(event);

            chngeRadio++;




              function replaceNode() {

             function replaceNode() {

             if (k === 1) {
                 //resets count to 0
                 chngeRadio -= 1;

             };


             if (k === 2) {
                 //resets count to 1
                 chngeRadio = 2;
                 chngeRadio -= 1;
             };


         };


         replaceNode()

             while (list.firstChild) {
                list.removeChild(list.firstChild);
            };



            for (var d = 0; d < 4; d++) {


                container = document.getElementById("container");
                list = document.getElementById("list");
                var li2 = document.createElement("input");
                li2.type = 'radio';
                li2.name = 'radio_group';
                li2.id = 'id2';
                li2.value = newQues.allQuestions[d].correctAnswer;
                li2.style.textAlign = "center";
                div2 = document.createElement("div");
                text2 = document.createTextNode(newQues.allQuestions[chngeRadio].choices[d])
                //alert(k);
                list.appendChild(div2);
                div2.appendChild(li2);
                div2.appendChild(text2);

            };

        };

    };


    };

Answer №1

My recommendation is to avoid using the functions chngeRadio and replaceNode() and instead replace them with k--. Additionally, modify the if condition in the Back btn.click to k>1.

if ( k > 1) {
    btn2.onclick = function (event) {
        event = EventUtil.getEvent(event);
        k--;

        while (list.firstChild) {
            list.removeChild(list.firstChild);
        };

        for (var d = 0; d < 4; d++) {
            container = document.getElementById("container");
            list = document.getElementById("list");

...

        text2 = document.createTextNode(newQues.allQuestions[k].choices[d]);
        //alert(k);
        list.appendChild(div2);
        div2.appendChild(li2);
        div2.appendChild(text2);
    };
};

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

What is the best way to structure a nested JSON object to align with a nested HTML form layout?

Currently, I am working on a form that is structured using tabs, optional fieldsets, and various field elements in HTML. Below is a simplified representation of the structure: div.tab1 div.fieldset3 div.container308 div.container314 div.fieldset4 d ...

Guidelines for validating email input using jQuery

Although I am not utilizing the form tag, you can still achieve form functionality using jQuery Ajax. <input type="email" placeholder="Email" name="email" /> <input type="password" placeholder="Password ...

Single jQuery scrolling loader malfunctioning in WebKit browser

I've been conducting an interesting experiment in which new entries are dynamically loaded onto a page as you scroll down. Check out a practical demonstration here. In Firefox, everything seems to be working perfectly. However, when viewed in WebKit ...

Steps to creating a popup within an HTML page from another HTML page

I recently started learning JavaScript. I have a link on my homepage that directs to another HTML page, but I would like it to show as a popup on the homepage with responsiveness and some stylish design elements such as a folded corner. Is there a way to a ...

Dynamic Bootstrap Tab menu slider with movable functionality when the limit is reached

I am facing an issue with the tabs menu on my website. The tabs menu items can vary between 2 or 3 to even 20 or more. When the number of navigation items exceeds 10, they automatically drop to the second line, which you can see here. However, I don' ...

What is the process for performing the "extract function" refactoring in JavaScript?

Are there any tools for extracting functions in JavaScript similar to the "extract function" refactoring feature available for Java and jQuery developers in Eclipse or Aptana? Or perhaps in another JavaScript/jQuery IDE? ...

Deactivating a form field depending on a selected radio button in Angular 2

If I have two radio buttons, with a click function called localClick for the first button to give value 1 and the second button to give value 2. <div class="ui-g-12"><p-radioButton name="group1" value="Local" (click)=localClick(1) label="Local"&g ...

Jquery: Pressing Enter will cause the input field to lose

Take a look at this fiddle I created: http://jsfiddle.net/7wp9rs2s/. This is the progress I have made on my project so far. In the fiddle above, you can double click on one of the 4 items and a textbox will appear for editing. Instead of clicking out of t ...

Configure the input to accept integer values

This page that I have developed is designed for entering Latitude and Longitude values. <div class="container "> <form class="entry"> <div class="aligncenter"> <h5 style="color:MediumTurquoise; font ...

Exploring the loading of stateful data in ReactJS and implementing optimizations

Exploring the world of ReactJS in conjunction with Django Rest Framework (DRF) def MyModel(model): ... status = ChoiceField(['new', 'in progress', 'completed'...]) In my application, I have dedicated sections for eac ...

Tips for displaying two input decorations in Material UI beside one another within a text field

In the Text Field demonstration, I noticed input adornments at the start and end. However, I am looking to have two input adornments at the end specifically. I attempted to add them using endAdornment: {InputAdornment InputAdornment}, but encountered an er ...

Troubleshooting disappearing values in POST request using ajax and jQuery serialize() method

When I make a post request, I am only able to retrieve two out of four values. I am expecting to get the id, step, name, and email from the form but the only ones I receive are from the hidden inputs. It seems like the jQuery serialize() function might be ...

Graphing functions with three.js

Is it possible to create a function grapher using the three.js API to plot a function in the form of z=f(x,y)? The program should: Generate input values between -1 and 1 in increments of .1, and use these values to plot x, y, and z vertices as part of a ...

Click the button to send the form without including any hidden HTML element array value

My main goal is to create a dynamic dropdown menu for users when they click a button. Each click triggers a new dropdown to appear. To achieve this, I have been cloning a hidden div each time the button is clicked. Here's an example of how I am accom ...

Move the absolute div by sliding it to the left from 120% to -10px

I want to move an absolute positioned div from the left side of the screen to -10px on button click. Here's my attempt so far, but it's not working as expected. Javascript/jQuery $('.button').click(function() { $(this).parent().f ...

The Photoswipe default user interface cannot be located

While attempting to incorporate PhotoSwipe into my website, I encountered an uncaught reference error related to The PhotoswipeUI_Default is not defined at the openPhotoSwipe function Below is the code snippet that I have been working on: <!doctyp ...

Retrieving information in JSON format

My goal is to retrieve data from the info.php file in order to utilize it in my project. This is what the content of info.php looks like: <?php $dbh = new PDO('mysql:host=localhost;dbname=csgo', 'root', ''); $sth = $dbh ...

Enhancing OpenAI API Responses with WebSocket Streaming through Express Middleware Integration

  Currently, I am in the process of developing an Express.js application that requires integration of OpenAI's streaming API responses to be transmitted in real-time to a front-end via WebSockets. Even though I have established communication between ...

A guide on triggering a function in Angular 6 when scrolling up or down

Is there a way to trigger a function when a user scrolls up or down in an Angular 6 project? I want to implement a feature similar to fullpage.js in my Angular 6 application. I initially attempted to achieve this using Angular animations, but without succ ...

Encountering the error of receiving "$ undefined," despite making a reference to the library

I have included the JQuery library in the following way: <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script> Despite trying to download the library and include it locally in my project, I ...