Navigating through radio button groups in AngularJS

I am currently developing a survey application using AngularJS. My goal is to display tasks one at a time, each containing one or more questions with radio button answers. I am looking to store the question and answer pairs in a new array.

While I have managed to extract answer values from radio buttons for individual questions, I am facing challenges when dealing with multiple questions and radio button groups on a single page. I am struggling to find a method to collect the selected radio button values and add them to the answers array. I have come across suggestions involving ng-model but haven't been able to implement it successfully.

Here is my current code snippet: https://jsfiddle.net/8qfom9th

<div ng-app="surveyApp" ng-controller="surveyCtrl">
<div ng-repeat="questionSet in questionSet">
    <div ng-if="question_index == $index">


          <div ng-repeat="onePageQuestions in questionSet.onePageQuestions">

            <div ng-repeat="question in onePageQuestions.question">
              {{question.description}}

              <form action="">

              <div ng-repeat="options in question.options">
                  <input type="radio" name="gender" ng-model="question.random" ng-value="options.answer"> {{options.answer}}
              </div>

            </form>

            </div>

          </div>

    </div>
</div>
<hr>
<button ng-click="next(); submitAnswers()">Next</button>

Answer №1

Hey there, it's actually quite simple my friend.

To retrieve the value of the selected button, you can utilize the checked property. Given that only one radio button can be selected within a group, obtaining the value of the selected option becomes straightforward using this property in an if loop in JavaScript.

  • As you have already assigned a name to the radio buttons' options, such as gender, you can easily access all the option elements by using the following:

    var options = document.getElementsByName('gender');
    var option_value; //to store the selected value
    
  • The next step involves looping through all the buttons to identify which one is selected. To achieve this, employ a for loop like this:

    for (var i = 0; i < options.length; i++) {...}

    To determine if a button is selected or not, check the checked attribute as shown below:

    if (options[i].checked) {
        option_value = options[i].value;
    }
    

If you intend to display these values but are unsure about what to do with them, I've assumed that you need to showcase them. In that case, create another element, perhaps a <div>, and assign it an ID. Then simply append the selected option value to that element. Here's how you can do it:

HTML:

<div id="selected">The selected options are:</div>

JS:

document.getElementById('selected').innerHTML += "<br>" + option_value;

Check out the updated fiddle.

Or if you want to test it right here, see the modified code snippet below:

// AngularJS module
var app = angular.module('surveyApp', []);

// AngularJS controller
app.controller('surveyCtrl', function($scope) {
  $scope.questionSet = [{
      onePageQuestions: [{
        question: [{
            description: 'question#1?',
            options: [{
              answer: 'answer#1'
            }, {
              answer: 'answer#2'
            }, {
              answer: 'answer#3'
            }]
          },
          {
            description: 'question#2?',
            options: [{
              answer: 'answer#4'
            }, {
              answer: 'answer#5'
            }, {
              answer: 'answer#6'
            }]
          }
        ]
      }},
      {
        onePageQuestions: [{
          question: [{
            description: 'question#3?',
            options: [{
              answer: 'answer#7'
            }, {
              answer: 'answer#8'
            }, {
              answer: 'answer#9'
            }]
          }]
        }]
      }
    ];
    
    $scope.question_index = 0;

    $scope.next = function() {
      if ($scope.question_index >= $scope.questionSet.length - 1) {
        $scope.question_index = 0;
      } else {
        $scope.question_index++;
      }

    };

    $scope.submitAnswers = function() {

      var options = document.getElementsByName('gender');
      var option_value;
      for (var i = 0; i < options.length; i++) {
        if (options[i].checked) {
          option_value = options[i].value;
          document.getElementById('selected').innerHTML += "<br>" + option_value;
        }
      }
    };
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="surveyApp" ng-controller="surveyCtrl">
  <div ng-repeat="questionSet in questionSet">
    <div ng-if="question_index == $index">


      <div ng-repeat="onePageQuestions in questionSet.onePageQuestions">

        <div ng-repeat="question in onePageQuestions.question">
           {{question.description}}
           <form action="">

             <div ng-repeat="options in question.options">
               <input type="radio" name="gender" ng-model="question.random" ng-value="options.answer"> {{options.answer}}
             </div>

           </form>

         </div>

       </div>

     </div>
   </div>
   <hr>
   <button ng-click="next(); submitAnswers()">Next</button>
   <hr>
   <div id="selected">The selected options are:
   </div>
</div>

Answer №2

Utilize parent.answer for the ng-model attribute to implement dynamic radio buttons. In addition, I have included a saveAnswers function tailored to manipulate and store user responses.

Below you will find the demonstration code for your specific scenario. Run the code to observe the updated questionSet in the console.

var app = angular.module('surveyApp', []);

app.controller('surveyCtrl', function($scope) {
  $scope.answer = '';
  $scope.saveAnswers = function(description, options) {
    $scope.questionSet.map(function(value, key) {
      value.onePageQuestions.map(function(item, index) {
        item.question.map(function(question, count) {
          if (question.description === description.description) {
            question.answer = options;
          }
        })

      })
    })
  }
  $scope.questionSet = [{
      onePageQuestions: [{
        question: [{
            description: 'question#1?',
            answer: '',
            options: [{
              answer: 'answer#1'
            }, {
              answer: 'answer#2'
            }, {
              answer: 'answer#3'
            }]
          },
          {
            description: 'question#2?',
            answer: '',
            options: [{
              answer: 'answer#4'
            }, {
              answer: 'answer#5'
            }, {
              answer: 'answer#6'
            }]
          }
        ]

      }]
    },
    {
      onePageQuestions: [{
        question: [{
          description: 'question#3?',
          answer: '',
          options: [{
            answer: 'answer#7'
          }, {
            answer: 'answer#8'
          }, {
            answer: 'answer#9'
          }]
        }]
      }]
    }]
  ];
  
  $scope.question_index = 0;

  $scope.next = function() {
    if ($scope.question_index >= $scope.questionSet.length - 1) {
      $scope.question_index = 0;
    } else {
      $scope.question_index++;
    }
  };

  $scope.submitAnswers = function() {
    console.log($scope.questionSet)
  }

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>

<div ng-app="surveyApp" ng-controller="surveyCtrl">
  <div ng-repeat="questionSet in questionSet">
    <div ng-if="question_index == $index">
      <div ng-repeat="onePageQuestions in questionSet.onePageQuestions">
        <div ng-repeat="question in onePageQuestions.question">
          {{question.description}}
          <form action="">
            <div ng-repeat="options in question.options">
              <input ng-change="saveAnswers(question,options.answer)" type="radio" name="gender" ng-model="$parent.answer" ng-value="options.answer"> {{options.answer}}
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
  <hr>
  <button ng-click="next()">Next</button>
  <button ng-click="submitAnswers()">Submit</button>

I trust this information proves beneficial to you!

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 method for ensuring that the field in $mdDialog.prompt() is mandatory?

Take a look at their demo script. How can I make sure that the field must be filled in? var confirm = $mdDialog.prompt() .title('Choose a name for your dog') .textContent('Bowser is a popular choice.') .placeholder('Dog name ...

Having trouble getting THREE.Raycaster to intersect with THREE.PointCloud

Currently, I am trying to implement click events on my WebGL based 3D graph library called Graphosaurus. You can take a look at what I have done so far here. I have used this example as a reference. I am wondering if the reason it is not functioning corr ...

Updating Directive on State Changes: A Step-by-Step Guide

Within my Angular template, I have implemented a root state that sets the overall structure. This root state includes a sidebar with dynamic menus that change based on the current state. Here is an example: .state(‘root', { abstract: tr ...

Is this jQuery script correct?

function like(){ $('#likeo').html('<div style = "align:center"><img src = "images/loader.gif"></div></br>').show(); var pid = <?php echo $post; ?>; $.post('include/like.php',{pids:pid} ...

What measures can be taken to prevent the reloading of a subfolder within the same parent in the Fuel

var DataSourceTree = function (options) { this.source = options.source; } DataSourceTree.prototype = { data: function (options, callback) { var self = this; var ...

AngularJS ng-focus does not function properly with iframes

Why isn't ng-focus working with iframe in AngularJS? What am I missing? Take a look at my code: <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script> <iframe src="example.com" tabindex="-1" ng-fo ...

What could be the reason for the input.autocomplete feature failing to erase the existing history in my form? (HTML/JS)

const form = document.querySelector("#contact-form"); const feedback = document.querySelector(".feedback"); const patternName = /^[a-z A-Z]{3,25}$/; form.addEventListener("submit", (e) => { e.preventDefault(); const firstn ...

Can you explain the distinction between using useContext and Redux?

Can you explain the distinction between useContext and Redux? Is Redux similar to using useContext? Do I no longer require useContext when implementing Redux in my project? ...

"Retrieving the most recent data within an ng-repeat directive using AngularJS

I am facing an issue with ng-repeat in my application. It successfully fetches values from the database and displays them in input text fields. However, when I update these values and click the save button, the updated values are not being saved. Can someo ...

Using jQuery to update a table, however, the browser is failing to automatically refresh the

I have developed a node.js and sockets app to create a Single Page Application (SPA). The user can fill out a form to create a new lobby. Upon submission, a socket event is sent to the server, where the new lobby is added. The server then emits an event to ...

Unable to display modal pop-up in ASP.NET Core MVC web application

I have developed a web application using ASP.NET CORE MVC. I encountered an unusual issue while trying to display a modal popup using JQuery. The div structure I am working with is as follows: <div class="modal fade" tabindex="-1" r ...

Steps to display a full-page loader/spinner prior to the completion of loading a React application

What is the best way to create a full-page loader/spinner that will be displayed until a React (or other JS-based framework) app is fully loaded? By "fully loaded," I mean when the browser's spinner stops spinning. I have experience creating loaders ...

What is the best way to specifically install the angular-ui-router.js file without the whole npm source code solution?

After installing the angular package using npm, I found the necessary JS files in the angular root directory. $npm install angular However, when installing the angular-ui-router package, I received the entire source code solution along with the required ...

Unable to find / DELETE Express.js

Within my script, I am attempting to perform POST, GET, and DELETE operations. Whenever I use POST or GET, the correct messages are logged. However, whenever I attempt to use DELETE, I encounter the following error: Cannot GET /del_user The URL I have ...

What advantages come from selectively importing a single function from a Node.js package on the backend, rather than importing the entire package?

Consider a scenario where I only require the ObjectId function from the mongoose package in my file. Are there any advantages (in terms of CPU usage, memory consumption, speed, etc.) to importing just that specific function instead of the entire mongoose ...

Retrieve and utilize the dynamically produced values from the application's app.js in a script that is accessed using

In my Express.js Node web app, I generate a string in app.js during initialization: // app.js var mongourl = /* generated based on process.env.VCAP_SERVICES constant */; There is a script that I import into app.js using require(): // app.js var db = req ...

What's the best method for concealing components: using a class to hide or removing them from the

I am encountering difficulties in React as I try to add a class to a component after a specific time duration. My goal is to apply the "hidden" class to a loading image, changing it to display: none after a few seconds. However, despite my efforts, I keep ...

JQuery's is() function is returning a true value

I am facing a dilemma with a particular string that can either represent text or an anchor tag with text. I have implemented some logic to always return the text in the following way: $(text).is('a') ? $(text).text() : text; The idea behind ...

Displaying the structure of a MongoDB database using Express and Angular in a tabular format

I am looking to present the data from MongoDB in a table format using HTML along with Node.js, Express.js, and Angular.js. Currently, my approach is as follows: route.js app.get('/superhero', function(req, res) { superhero.superhero_list(r ...

Ways to stop the react-router from causing the page to refresh

Need assistance with React Router issue I'm working on a project in reactJs using react-router-dom v5. I have set up a default route for routing. <Redirect to={"someComponent"}/> The problem is that when I refresh the page, it auto ...