Executing a for loop just once in JavaScript

var door1 = {open: false,car: false,choose: false};
var door2 = {open: false,car: false,choose: false};
var door3 = {open: false,car: false,choose: false};

var carName = 0;
var objectName = 0;
var goatName = 0;
var min = 1;
var max = 4;
var random = Math.floor(Math.random()*(max - min) + min); 
var objectRandomName = "door" + random;
window[objectRandomName].car = true;
for (var jj = 1; jj < 4; jj++){
    objectName = "door" + jj;
    carName = "car" + jj;
    goatName = "goat" + jj;
    if (window[objectName].car == true){
        document.getElementById(carName).style.display = "block";
    }
    else{
        document.getElementById(goatName).style.display = "block";
    }
}

The loop should iterate three times, but it's only running once. I'm confused as to why this is happening.

Here's the relevant HTML code:

<div id="main">
    <div id="door1">
        <div id="InDoor1">
        </div>
        <div id="goat1"></div>
        <div id="car1"></div>
        <div id="spaceB"></div>
        <button type="button" id="Bdoor1" onclick="ChooseDoor(1);">דלת 1</button>
    </div>
    <div class="space"></div>

    <div id="door2">
        <div id="InDoor2">
        </div>
        <div id="goat2"></div>
        <div id="car2"></div>
        <div id="spaceB"></div>
        <button type="button" id="Bdoor2" onclick="ChooseDoor(2);">דלת 2</button>
    </div>
    <div class="space"></div>

    <div id="door3">
        <div id="InDoor3">
        </div>
        <div id="goat3"></div>
        <div id="car3"></div>
        <div id="spaceB"></div>
        <button type="button" id="Bdoor3" onclick="ChooseDoor(3);">דלת 3</button>
    </div>
    <div class="space"></div>

</div>

I need the script to change the display property from "none" to "block". The initial CSS setting for display is set to "none."

Answer №1

Errors may arise that hinder execution due to the onload event not making window[objectRandomName] globally available.

To avoid these errors, consider moving the declarations outside the onload function to ensure the variables are in the global scope.

Alternatively, you can create your own variables instead of using the fix provided below:

var door1 = {open: false,car: false,choose: false};
var door2 = {open: false,car: false,choose: false};
var door3 = {open: false,car: false,choose: false};

var carName = 0;
var objectName = 0;
var goatName = 0;
var min = 1;
var max = 4;
var random = Math.floor(Math.random()*(max - min) + min); 
var objectRandomName = "door" + random;
window.onload=function() {
  window[objectRandomName].car = true;
  for (var jj = 1; jj < 4; jj++){
    objectName = "door" + jj;
    carName = "car" + jj;
    goatName = "goat" + jj;
    console.log(objectName,objectRandomName)
    if (window[objectName] && window[objectName].car == true){
        document.getElementById(carName).style.display = "block";
    }
    else{
        document.getElementById(goatName).style.display = "block";
    }
  }
}
#car1, #car2, #car3, #goat1, #goat2, #goat3 { display:none }
<div id="main">
    <div id="door1">
        <div id="InDoor1">
        </div>
        <div id="goat1">G1</div>
        <div id="car1">C1</div>
        <div id="spaceB"></div>
        <button type="button" id="Bdoor1" onclick="ChooseDoor(1);">דלת 1</button>
    </div>
    <div class="space"></div>

    <div id="door2">
        <div id="InDoor2">
        </div>
        <div id="goat2">G2</div>
        <div id="car2">C2</div>
        <div id="spaceB"></div>
        <button type="button" id="Bdoor2" onclick="ChooseDoor(2);">דלת 2</button>
    </div>
    <div class="space"></div>

    <div id="door3">
        <div id="InDoor3">
        </div>
        <div id="goat3">G3</div>
        <div id="car3">C3</div>
        <div id="spaceB"></div>
        <button type="button" id="Bdoor3" onclick="ChooseDoor(3);">דלת 3</button>
    </div>
    <div class="space"></div>

</div>

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

The cookies() function in NextJS triggers a page refresh, while trpc consistently fetches the entire route

Is it expected for a cookies().set() function call to trigger a full page refresh in the new Next 14 version? I have a chart component that fetches new data at every interval change, which was working fine when fetching the data server-side. However, since ...

Storing information in a session within a callback function using Node.js Express

Within the following code snippet, my goal is to retrieve user information from the database and store it in a session. However, I am encountering an issue where the data is not being properly saved into the session variable as expected. Could this be du ...

The usage of arrow functions in ReactJS programming

I'm working on a React component that has the following structure: import React, { PropTypes, Component } from 'react'; import { Accordion, Panel, PanelGroup, Table } from 'react-bootstrap'; const FormCell = ({ data }) => ( ...

View cards from a restricted Trello board without requiring visitors to have a Trello account or to authorize through a popup

I have a company with ongoing projects listed on a private Trello board. We are interested in showcasing these projects on our website in real-time by connecting to the board. After implementing this example, I can successfully retrieve and display the ca ...

Deleting an item from a Vue.js list

I'm currently working on a project to develop a basic webpage that allows users to add or remove textboxes using vue.js. new Vue({ el: "#app", data() { return { list: [] }; }, methods: { deleteFromList(index) { this ...

Unlocking the secrets of obtaining post values using Body-parser in your Express Node.js application

Currently, I am utilizing Express version 4.11.1 and Body-parser version 1.11.0 in my project. However, upon running the code snippet below, I encountered the following output: I am seeking suggestions on how to retrieve the form value. Output {} serve ...

Navigating a double entry validation in a Java script prompt while utilizing Selenium

Can someone please assist me with the following scenario: I need to complete a double entry check prompt/alert that contains two text boxes. The task is to fill in these two text boxes and then click on the OK button. Potential solutions attempted: I tr ...

Issue: angular2-cookies/core.js file could not be found in my Angular2 ASP.NET Core application

After spending 2 hours searching for the source of my error, I have decided to seek help here. The error message I am encountering is: "angular2-cookies/core.js not found" I have already installed angular2-cookie correctly using npm. Below is the code ...

Establish the following 13 steps to configure the initial server state and retrieve the client state

Currently, I have 13 applications and I am utilizing Zustand as my state manager. Below is a simple layout example: <MainProvider> <div className="min-h-screen flex flex-col"> <Navbar></Navbar> <main className ...

Send a signal to a space, leveraging the distinct characteristics of each socket as input parameters

I am looking to send a function to a group of sockets, with each socket receiving the function along with a specific parameter unique to that particular socket. In my coding scenario, this distinctive variable represents the player's number. As socke ...

Successfully resolving the API without encountering any response errors, even after sending a response

Once the data is successfully saved in the database and the image upload is completed, I am attempting to send res.json. However, I keep encountering the error message API resolved without sending a response for /api/auth/registeration, this may result in ...

Valid method of confirming a user's login status

Using AJAX requests, I have implemented a user area on my website. The "Log off" button is supposed to be displayed only when the user is logged in. Here is the AJAX request for logging in a user: function requestSI() { var xhr = getXMLHttpRequest(); xhr ...

Load texture using ImageUtils with callback in Canvas Renderer

Currently, I am utilizing three.js revision 53. While attempting to load a texture in Canvas Renderer (specifically on Win7) and incorporating a callback for the onLoad event, the texture fails to display. Surprisingly enough, removing the callback functi ...

Access all the properties of an object within a mongoose record

My database contains a collection of documents that are structured using the mongoose and express frameworks. Each document follows this schema: const userSchema = new Schema({ firstName: { type: String }, lastName: { type: String }, email: { t ...

What could be causing the misalignment between the desired output and the response from the AJAX request

Below is a basic JavaScript file I am working with: $.ajax({ url: "is_complete.php", type: "post", success: function (data) { if(data == 1) { } alert("ok") } }) The message "ok" will only be di ...

Tips for initiating a function at a designated scroll point on a webpage

Currently, I am testing out a code snippet that allows images to flip through in a canvas element. I'm curious if it's possible to delay the image flipping effect until the viewer scrolls down to a specific section of the page where the canvas i ...

issues with jquery's .each() method not functioning properly

I am looking to iterate over each item in lists and then each list within lists to calculate the number of items in list if the number of items in list is 3, I want to display an alert with the value of each item JSON Data { "lists":[ { ...

Verify that the select field has been chosen using Protractor

Currently, I am in the process of developing a test that places importance on whether a select field has already been populated. it('should automatically select a field if it hasn't been selected previously', function() { var usersField = ...

The Node.js Express server does not provide access to certain static files

I am currently utilizing the angularjs-gulp-browserify-boilerplate for my development environment on Windows 10. Once I run gulp in dev mode, static files are moved to the build directory: ./build |_js |_css |_img |_fonts |_lang In additio ...

Can JavaScript event listeners be compelled to trigger in a specific sequence?

Is there a way in JavaScript to receive notification or execute a callback function once an event has completed its propagation? Put differently, is it possible to 'prioritize' an event and ensure that it gets triggered after all other event lis ...