Using an Embedded For Loop within an If Statement in JavaScript/jQuery

Ensuring that at least one radio button for each question in my quiz is checked before allowing a user to submit was achieved by using a for loop within an if statement. Below is the code snippet:

HTML:

<form name="quizform">
            <div id="quizpart1">
                <h2>Title</h2>
                <br>
                <div id="notfinished1">
                </div>
                <br>
                    <!---Question 1: --->
                    <div class="row">
                        <div class="col-xs-8">
                            <label>1) Have you ever ...?</label>
                        </div>
                        <div class="col-xs-4">
                            <input type="radio" name="heartAttack?" value="true">Yes</input>
                            <br>
                            <input type="radio" name="heartAttack?" value="false">No</input>
                        </div>
                    </div> 

The HTML structure for other questions in the form follows a similar format as above.

Javascript:

//Variables
var quizpart1names = ["heartAttack?", "familyHeartDisease?", "congenitalHeartDisease?", "lungDisease?", "currentHeartThyroidDisease?"];

//For Loop With If Statement as a Conditional
if (
        for (i=0; i < quizpart1names.length; i++){
            $('input[name=quizpart1names[i]]:checked').length > 0;
        }
    ){ //Used the jQuery Function :checked, with the logic behind .length > 0 indicating that both "true" and "false" options have length > 0.
        $("#quizpart1").hide();
        //... The remaining code functions correctly when not checking if all quiz questions were answered.

However, I encountered an issue where none of the JavaScript functionalities, including this example, work on Firefox browser after running the webpage. Any help in understanding and resolving this problem would be appreciated.

Answer №1

Expressions cannot contain statements like for.

To filter out items where the condition is true, you can utilize the grep method and then determine how many items remain.

If you want any of the conditions to be true:

if (
  $.grep(quizpart1names, function(q){
    return $("input[name='" + q + "']:checked").length > 0;
  }).length > 0
) {
  ...
}

If you require all of the conditions to be true:

if (
  $.grep(quizpart1names, function(q){
    return $("input[name='" + q + "']:checked").length > 0;
  }).length == quizpart1names.length
) {
  ...
}

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

Dynamic Search Functionality using Ajax and JavaScript

function fetchData(str) { if (str.length == 0) { var target = document.querySelectorAll("#delete"); return; } else { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && ...

Issue with unbinding events in Angular directive persists despite efforts to completely unbind

Our directive features a popup that loads a template with a directive to capture all clicks in the document. When a click is detected, it sends an event to close the popup and unbinds the event on the $document. This directive effectively captures docume ...

Encountered a CastError in Mongoose when trying to cast the value "Object" to a string

I am struggling with a Mongoose CastError issue within my Node.js API. The problem arises at a specific route where data is being returned appended with some additional information. Despite finding various solutions for similar problems, my scenario seems ...

discord.js: Bot keeps sending duplicate embeds

I recently set up my discord bot to respond with a message when I enter a specific command, but I've run into an issue where it's sending the same embed twice. I've tried troubleshooting, but so far I haven't been able to pinpoint the c ...

NgFor is failing to display data from a fully populated array of objects

CLICK HERE FOR THE IMAGE So, let's tackle the issue at hand. I have an array that contains data fetched from an API. These data points are essentially messages. Now, below is the TypeScript file for a component where I aim to display all these messag ...

Class methods cannot be invoked within their constructor

I'm currently facing challenges with implementing my express router. This is a "subrouter" of my main router, hence I need to extend express.Router. Here's an example of the code (simplified to include only one method): import express from "expr ...

What could be the culprit behind the error in the "blend-mode" function when using .mp4 files in Firefox?

Attempting to utilize mix-blend-mode with an mp4 playing in the background has been a fun experiment. The concept is to have a div containing some text, with the video playing in the background to create an effect on the letters. This method works flawless ...

Tips for retrieving the final element from a corrupt JSON string using JavaScript

I've encountered an issue with a nodejs speech recognition API that provides multiple texts in a JSON like structure which renders the data invalid and useless. { "text": "Play" } { "text": "Play astronaut" } ...

Ways to utilize jQuery for selecting IDs that are not part of a specific class

I am currently working with a jQuery script that is designed to target all IDs containing 'Phone'. However, I am facing an issue where I need the selection to ignore those IDs if they are part of a specific class. The current code I have, from m ...

Querying cookies using Jquery/Ajax

Is there a way to trigger an ajax call when a page detects the presence of a cookie? I'm having trouble getting the ajax call to work in the code below. Any assistance would be greatly appreciated. EDIT: I have updated the code and it is now function ...

Manipulating parent based on first child using CSS

Is it possible to manipulate the parent element using CSS based on the presence of a specific child? For instance, I want to style a table cell differently if the first child within it is a link. <td>Hello</td> <td><a href="go.html"& ...

What is the best way to utilize typed variables as types with identical names in Typescript?

Utilizing THREE.js with Typescript allows you to use identical names for types and code. For instance: import * as THREE from '/build/three.module.js' // The following line employs THREE.Scene as type and code const scene: THREE.Scene = new THRE ...

Incorporate personalized feedback into a datatable with server-side processing

Trying to implement server-side processing for a datatable loaded from an AJAX response using this specific example The server response being received is as follows: {"msg":null,"code":null,"status":null,"result":[{"aNumber":"3224193861","bNumber":"32159 ...

Angular’s ng-repeat function is behaving erratically as objects are displayed in the console

Having trouble with my ng-repeat not displaying content. Here is the code for my app.js, client controller, factory, and server controller. Everything else seems to be working fine. I can see all the console logs in Chrome and terminal, but the ng-repeat ...

Using Array.Map() to retrieve the child array within a React component

Here is the data I have retrieved from an API: [ { "id": 1, "appName": "string", "defaultAction": "string", "defaultMessage": "string", "rules": [ { "id": 1, "version": "string", "brand": "string", ...

Discovering applied styles based on component props in Material-UI v5 using browser developer tools

When working with Material UI v4, I found it easy to identify which styles are applied by component props classname using browser dev tools. This allowed me to override specific styles of the component effortlessly. However, in Material UI v5, I am unsure ...

The navigation bar in responsive view on Bootstrap 4 causes the content below it to shift

Recently I have been exploring bootstrap-4 and encountered an issue while creating a nav-bar. The problem is that in responsive view, when toggling the nav-bar it simply pushes the content below it. Is there any way to address this issue within (bootstra ...

Utilizing AJAX to call a web service

Trying to make a call to this web service via AJAX... The structure of the web service is as shown below public class WebService1 : System.Web.Services.WebService { [WebMethod] public String countryCo ...

What is the best way to connect specific nodes to the edge of a canvas in cytoscape and create perfectly straight lines?

In the center column of my article, I have two graphs created with cytoscape showing "ancestors" and "descendants" on the sides. I am interested in displaying the connections ("edges") from the articles in the final generation of "ancestors" to the articl ...

The jQuery function .val()/.text() is unable to retrieve information from a particular section of HTML

Implementing HandlebarsJS with PHP and Yii to generate a page. Here is a snippet of the html/handlebars code on the page {{#if embed_link}} <p class='f_hidden_p'> <a href='{{embed_link}}'> {{ ...