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

Does the language setting on a browser always stay consistent?

Using javascript, I am able to identify the language of my browser function detectLanguage(){ return navigator.language || navigator.userLanguage; } This code snippet returns 'en-EN' as the language. I'm curious if this i ...

Can a webpage be sent to a particular Chromecast device without using the extension through programming?

My organization has strategically placed multiple Chromecasts across our facility, each dedicated to displaying a different webpage based on its location. Within my database, I maintain a record of the Chromecast names and their corresponding URLs. These d ...

Filter the output from a function that has the ability to produce a Promise returning a boolean value or a

I can't help but wonder if anyone has encountered this issue before. Prior to this, my EventHandler structure looked like: export interface EventHandler { name: string; canHandleEvent(event: EventEntity): boolean; handleEvent(event: EventEntity ...

How to customize the arrow color of an expanded parent ExpansionPanel in material-ui

Currently facing a challenge in customizing material-ui themes to achieve the desired functionality. The goal is to have the expansion panels display a different arrow color when expanded for improved visibility. However, this customization should be appl ...

Merge arrays to form nested structures

Here's a mind-bending scenario for you. Imagine I have two arrays - one containing categories and the other containing arrays that follow the structure of those categories. For example: var categoryArray = ["Name", "Title", "Hire Date"]; var infoArr ...

How to Determine if Your Chrome Packaged App is Operating in Kiosk Mode

I'm in the process of developing an application that is able to function both in kiosk mode and regular mode (such as opening from a Chrome browser). However, I need certain features to be restricted to kiosk mode only. How can I determine if the appl ...

utilizing the data provided by a user in the "prompt" window within my HTML code

Looking to utilize user input from the prompt window. This is my custom JavaScript form: var answer; function load() { answer=prompt("what is your name?", "Write your name here"); return answer; } function hideNsee() { var HNS = docume ...

Expanding Image with HTML and CSS: A Guide

In the process of creating my website, I encountered an issue with the logo placement. I wanted the logo to be in the top left corner, similar to the one shown in this image. Initially, everything was working fine until I made some adjustments to move the ...

Attempting to retrieve user information from Blockstack on a web browser

Currently developing a web application integrating Blockstack and encountering challenges with Javascript implementation and understanding how to effectively use Blockstack in the browser. My issue arises when retrieving the Blockstack user's ID or u ...

Find the accurate street view on Google Maps URL without relying on computeheading

I've implemented the computeHeading code from a previous answer by Geocodezip, which is mostly effective but has some minor issues that are not related to Geocodezip. The resulting value from computeHeading is stored in the "heading" variable, which d ...

Tips on utilizing Sinon for mocking a function that triggers a REST request

I'm currently navigating my way through sinon and mocha, working on the code and test provided below. My goal is to test the findAll() method without triggering an http request. However, I've encountered an error with the current setup: [TypeErr ...

Display a div element on the page after 10 seconds of loading

Recently, I managed to get this script working successfully where it fades out within 20 seconds. However, I am looking to modify it so that it takes only 10 seconds to display after the page loads. Any suggestions on what I should change in the code? jQu ...

Resizing svg to accommodate a circle shape

As I work on my vue.js app that involves a plethora of diverse icons, I made the decision to create a small icons builder in node.js. The purpose is to standardize their usage and also "crop" each SVG so it fits perfectly within its parent container by uti ...

What is the best way to add controllers to AngularJS?

What is the best way to troubleshoot this setup? app.js var app = angular.module('app', ['ui.router', 'app.controllers']); /* Why is FooCtrl not being recognized here? */ controllers.js var controllers = angular.module(&a ...

Sending parameters in SwipeableDrawer in ReactJS using Material UI

This is a demonstration of my SwipeableDrawer from material-ui const sideList = ( </List> <ListItem button component={Link} to="/todos"> <ListItemText primary="Todos" /> </ListItem> </List> ) <SwipeableDrawer o ...

Pause the for loop until all nested asynchronous database calls are completed

Currently, I am utilizing the listCollection method within mongodb to loop through each collection that is returned using a query with find. The issue arises when I attempt to construct an object within the loop that I intend to return with response.json ...

Utilizing Node gRPC for seamless transmission of server metadata to clients without any issues

When working from the client side, adding metadata for the server is a simple process: const meta = new grpc.Metadata(); meta.add('xyz', 'okay'); stub.service.Rpc(request, meta, (err, response) => { }); To access the above on the ...

Display the list of cities associated with the country chosen in the form

I am currently working with the repository found at https://github.com/country-regions/country-region-data/blob/master/data.js to create a mapping of countries and their related cities. I'm seeking guidance on how to achieve this task effectively. My ...

The grid items fail to refresh even after I have made changes to the useState in my React Native application

I am currently working on a react native project that includes a grid component. My goal is to update an array in the state called selectedHomeTypes whenever a user clicks on an item within the grid. Initially, the array is set to contain only one element: ...

Guide on setting up an Express application to control LED light strips with a Raspberry Pi3

After setting up a node server on my Raspberry Pi to control an Adafruit Dotstar light strip, I encountered a problem. The sequence of colors on the light strip is triggered by an HTTP request to localhost:8000/fade, causing the server to run fade.js endle ...