Utilizing JavaScript For Loops for Code Repetition

Apologies for the ambiguous question title - struggling to articulate this properly.

Essentially, I have some JavaScript code that I am looking to streamline by using a for loop.

$('.q1').keyup(function () {
    if ($.inArray($(this).val().toLowerCase(), a1) > -1) {
        //Perform certain actions
    } else {
        //Do other things
    };
});

$('.q2').keyup(function () {
    if ($.inArray($(this).val().toLowerCase(), a2) > -1) {
        //Perform certain actions
    } else {
        //Do other things
    };
});

It is evident that the only difference between these two functions is the first class (either .q1 or .q2) and the array name (a1 or a2).

Up until now, I have accomplished the following...

for (var i=1; i<=8; i++) {
    $('.q'+i).keyup(function () {
        if ($.inArray($(this).val().toLowerCase(), a1) > -1) {
            //Perform certain actions
        } else {
            //Do other things
        };
    });
}

The issue with varying the array value on each iteration in order to cycle through a1, a2, a3, and so on remains unresolved.

Any assistance would be greatly appreciated. Thank you.

UPDATE

a1 and a2 correspond to arrays...

var a1 = new Array();
a1[0] = "egypt";

var a2 = new Array();
a2[0] = "brasil";
a2[1] = "brazil";

I have a distinct array for each quiz answer, housing all possible responses for every question.

Answer №1

For this type of problem, one commonly used data structure is arrays. They are more efficient for handling multiple variables in such scenarios.

Assuming you have an array called a, you can use the following code:

for (var i=1; i<=8; i++) {
  (function(answers){
    $('.q'+i).keyup(function () {
        if ($.inArray($(this).val().toLowerCase(), answers) > -1) {
            $('#r').text('ok');
        } else {
            $('#r').text('not ok');
        };
    });
  })(a[i-1]);
}

To initialize your array, you would do something like this:

var a = [];
a.push([
   "egypt"
]);
a.push([
   "brasil",
   "brazil"
]);

Check out the demonstration here

Answer №2

Transform this: var a1 = new Array(); a1[0] = "egypt";

var a2 = new Array();
a2[0] = "brasil";
a2[1] = "brazil";

into this:

var a = new Array();
a.push(["egypt"]);
a.push(["brasil","brazil"]);

Therefore,

a[0][0] == a0[0] == "egypt"

a[1][0] == a1[0] == "brasil"

a[1][1] == a1[1] == "brazil"

Subsequently, the if statement would be:

for (var i=1; i<=8; i++) {
    $('.q'+i).keyup(function () {
        if ($.inArray($(this).val().toLowerCase(), a[i-1]) > -1) {
            //Execute this code
        } else {
           //Run another code
        };
   });
}

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

Step-by-step guide on clipping a path from an image and adjusting the brightness of the remaining unclipped area

Struggling to use clip-path to create a QR code scanner effect on an image. I've tried multiple approaches but can't seem to get it right. Here's what I'm aiming for: https://i.stack.imgur.com/UFcLQ.png I want to clip a square shape f ...

Exploring Typescript for Efficient Data Fetching

My main objective is to develop an application that can retrieve relevant data from a mySQL database, parse it properly, and display it on the page. To achieve this, I am leveraging Typescript and React. Here is a breakdown of the issue with the code: I h ...

What could be causing my array to update when the method is called live but not during unit tests?

One of my methods is called toggleSelect which adds and removes items from an array named selectedItems. This method functions perfectly when I test it live in the browser. However, when running unit tests, it does not seem to work as expected. Despite cal ...

What causes the slash URL to behave differently than other URLs when running through the middleware of NodeJS?

When I type http://localhost:3000/product into the browser, why do I see output for both '/' and '/product'? Take a look at this code snippet below. const express = require('express'); const app = express(); // http://loca ...

Having trouble sending data to API with Node, Express, and vanilla JavaScript POST form

I am currently utilizing Node JS along with Express JS in order to implement a form submission that pushes data into the database. Below is my form structure <form action="/pokedex/register/poke_submission" method="POST"> ...

Showcasing the time variance using javascript/jquery

I am currently using a datepicker to select dates, with the intention of calculating the difference between the chosen dates and then displaying an alert with the calculated difference. Unfortunately, I am encountering issues with getting the code to work ...

Having trouble with adding an event listener on scroll in React JS. Need assistance in resolving this issue

I'm having trouble adding an event listener for when a user scrolls in my web app. componentDidMount = () => { let scrollPosition = window.scrollY; let header = document.getElementById("topBar"); window.addEventListener(&ap ...

The eel feature results in no output

During my Python program development using the Eel module, I encountered an issue. The problem is that the eel.getImgSrc(path) function returns null when trying to retrieve image's byte data. Take a look at this example: -----web/main.js------ async ...

Is there a way to prevent the omission of zeros at the end in JavaScript when using Number.toString(2)?

I am facing an issue while trying to reverse a 32-bit unsigned integer by converting it to a string first. The toString(2) function is causing the zeros at the end to be omitted, leading to incorrect output. This is my code: var reverseBits = function(n) ...

What is the best way to verify multiple email addresses simultaneously?

Is there a method to validate multiple email addresses entered by users in a textarea? My current approach involves using ng-pattern for validation. ...

The routing feature functions properly on localhost but encounters issues on the live server

There seems to be an issue with this code. While it works perfectly on localhost, it doesn't function as expected on a live Apache server. I have already specified the homepage in the package JSON file and included an htaccess file. However, when acce ...

What is the best way to efficiently import multiple variables from a separate file in Vue.JS?

When working with a Vue.JS application and implementing the Vuex Store, I encountered an issue in my state.js file where I needed to import configurations from another custom file, specifically config.js. Upon running it, I received the following warning ...

Dynamically assigning column values based on object properties

I am currently utilizing the Ionic Framework along with its grid system that is reminiscent of Bootstrap. However, I believe my query leans more towards AngularJS than specific Ionic components. Here is what I have: <ion-col *ngFor="let col of row ...

Using Reactjs to create a custom content scroller in jQuery with a Reactjs twist

I am attempting to implement the Jquery custom scrollbar plugin here in my React project. Below is a snippet of my code: import $ from "jquery"; import mCustomScrollbar from 'malihu-custom-scrollbar-plugin'; ..... componentDidMount: function() ...

"Step-by-step guide on showcasing a specific blog post using its unique identifier in an Angular/Express/MongoDB application

I'm struggling to figure out how to retrieve a single blog post by its ID, especially since I am new to this. Currently, my main blog application has an ng-repeat functionality that fetches all posts. What I really want is the ability to click on a p ...

I often struggle with creating social media buttons using Material UI

Unfortunately, the code provided is not rendering social media icons or buttons as expected. In the initial lines, material UI icons/buttons were imported from the React Material UI library (IconButton / AlarmIcon). import './App.css'; impor ...

I'm currently facing difficulties trying to implement AJAX with JavaScript and PHP as the desired output is not being

My query is quite straightforward - why isn't the code functioning properly? I am attempting to have the text echoed in PHP displayed inside a div with the ID of "show". Interestingly, this works with a txt file but not with PHP or any other type of f ...

Are the two pieces of code distinct from each other in any way?

What is the most effective way to use a for loop? Is it necessary to define the variable before using it in a for loop, or can it be used without defining it beforehand? test_list = retrieve_list() for item in test_list: # do something or for item in ...

In what way can I incorporate additional functions or multiple functions within an Express route to modify database information?

Currently, I am working on a project that involves Express and MySQL. One of the challenges I am facing is retrieving data from a connection.query and then utilizing that data in other functions within the same route. My goal is to use the array created in ...

display PHP JSON information using jQuery AJAX

I'm completely new to this subject. I have a Json result that looks like the following : { "span": " 1", "numcard": "12", "chan": " Yes", "idle": "Yes", "level": "idle ", "call": "No ", "name": "" } My goal is to ...