Mirror index of an array to the id property with counter

//Invoke functions only after page has fully loaded
window.onload = init;


var boxes = [];

var counter = 0;

function Box(id, name, color, x, y) {
    this.id = id;
    this.name = name;
    this.color = color;
    this.x = x;
    this.y = y;
}

function init() {
    var generateButton = document.getElementById("generateButton");
    generateButton.onclick = generate;
    
    var clearButton = document.getElementById("clearButton");
    clearButton.onclick = clear;
}

function generate() {
    var data = document.forms.data;
    var textInput = document.getElementById("name");
    var name = textInput.value;
    if (name == null || name == "") {
        alert("Please give your Amazing Box a name");
        return;
    }
    
    var colorSelect = document.getElementById("color");
    var colorOption = colorSelect.options[colorSelect.selectedIndex];
    var color = colorOption.value;
    if (!color) {
        alert("Pick a color");
        return;
    }
     
    // Get count of boxes to create
	var boxCount = 0;
	var radioButtons = document.getElementsByName("amount");
	for(iRadio = 0; iRadio < radioButtons.length; iRadio++)
	{
		if(radioButtons[iRadio].checked)
		{
			boxCount = radioButtons[iRadio].value;
		}
	}

	if(boxCount == null || boxCount == 0)
	{
		alert("Select an amount of boxes to create");
		return;
	}

	// Create boxes
    for (i = 0; i < boxCount; i++) {
		var scene = document.getElementById("scene");
		var x = Math.floor(Math.random() * (scene.offsetWidth-101));
		var y = Math.floor(Math.random() * (scene.offsetHeight-101));
    for (counter = 0; counter < boxCount; counter++) {  
           var number = document.getElementById("div.id");         
           boxes.push(new Box());
           
            var div = document.createElement("div");
            div.id = "box" + i;
            div.style.left = x + "px";
            div.style.top = y + "px";
            div.style.backgroundColor = color;    
            div.setAttribute("class", "box");
            
            scene.appendChild(div);
            div.innerHTML = "Box of " + name + "<br />(click me)";
            
            
            div.onclick = function() {
                alert("You clicked on a box with id " + div.id + 
                ", named Box of " + name + ", whose color is " + color + 
                " at position " + div.style.top + ", " + div.style.left);
            
            
}            }
          
            data = document.getElementById("data");
            data.reset();
        }
    }


//Clear the boxes from scene div            
function clear() {
        var sceneDivs = document.querySelectorAll("div#scene div");
        for (var i = 0; i < sceneDivs.length; i++) {
            var scene = document.getElementById("scene");
            var cutList = document.getElementsByTagName("div")[1];
            scene.removeChild(cutList);
       }
     }

The idea is that the id property given to each div will mirror that of an index in the array for that box. So the div with the id 0 is a representation of the Box() object with the index 0 in the boxes array. That way when display is clicked, the id of the div which was clicked, will grab the Box() object at that index of the array, and show its properties in an alert.

Sounds good.
Where are you having trouble?
It would also help if you could provide a more complete example (i.e. include the HTML)

//Here is the HTML and CSS sheets

<!doctype html>
<html lang="en">
<head>
  <title> Final Project: Amazing Boxes </title>
  <meta charset="utf-8">
  <link rel="stylesheet" href="boxes.css">
  <script src="boxes.js"></script>
</head>
<body>
  <form id="data">
    <ol>
      <li>Pick a name for your Amazing Box: <br>
        <label for="name">Name: </label>
          <input type="text" id="name" size="20">
      </li>
      <li>Pick a color for your Amazing Box: <br>
        <select id="color">
          <option value="red">Red</option>
          <option value="orange">Orange</option>
          <option value="yellow">Yellow</option>
          <option value="green">Green</option>
          <option value="blue">Blue</option>
          <option value="indigo">Indigo</option>
          <option value="violet">Violet</option>
        </select>
      </li>
      <li>How many Amazing Boxes do you want to create?<br>
        <input type="radio" id="five" name="amount" value="5">
          <label for="five">5</label><br>
        <input type="radio" id="ten" name="amount" value="10">
          <label for="ten">10</label><br>
        <input type="radio" id="fifteen" name="amount" value="15">
          <label for="fifteen">15</label><br>
      </li>
    </ol>
    <p>
      <input type="button" id="generateButton" value="Generate!">
      <input type="button" id="clearButton" value="Clear">
    </p>
  </form>
  <div id="scene">
  </div>
</body>
</html>
//CSS
html, body {
    width: 100%;
    height: 90%;
    margin: 0px;
    padding: 0px;
    font-family: Helvetica, Arial, sans-serif;
}
                
input#generateButton {
    margin-left: 15px;
}
                
div#status {
    margin-left: 15px;
}
                
div#scene {
    position: relative;
    width: 100%;
    height: 80%;
    margin: 0px;
    padding: 0px;
}
                
div.box {
    position: absolute;
    width: 100px;
    height: 90px;
    padding-top: 10px;
    text-align: center;
    overflow: hidden;
}

Hi,

That seems to work.
I’m still not really sure what you are having trouble with.
Could you rephrase your question.

What I cant figure out is how to mirror the index of the array and apply it to the alert box. Lets say I picked 10 boxes, color red, named hello. The alert comes out as you picked a red box with an id of 9 named hello at 280 px and 140 px. I cant figure out how to start the numbering at 0 and the the last random box have an id of 9. Same goes with picking 5 boxes, it labels all of them at id4. Then after that is figured out I have to clear the array or shall I put it, reset the value to zero.

The first thing to note is that you have one for loop too many:

for (i = 0; i < boxCount; i++) {
  ...
  for (counter = 0; counter < boxCount; counter++) {
    ...
  }
}

Should be:

for (i = 0; i < boxCount; i++) {
  ...
}

Currently you are generating boxCount number of the same boxes, that is if you set boxCount to five, you are generating five of each box (where you only need one).

Your main problem is being caused by these lines:

div.id = "box" + i; 
....
div.onclick = fnction() {
  alert("Id " + div.id);
}

All of the onclick handlers you are creating share the same i variable. You need to put each handler into a separate function that takes i as a parameter so that each one gets its own copy.

Here’s a stripped down version of your code that works as intended:

<!doctype html>
<html lang="en">
<head>
  <title>Final Project: Amazing Boxes </title>
  <meta charset="utf-8">
    <style>
      html, body {
        width: 100%;
        height: 90%;
        margin: 0px;
        padding: 0px;
        font-family: Helvetica, Arial, sans-serif;
      }

      input#generateButton {
        margin-left: 15px;
      }

      div#status {
        margin-left: 15px;
      }

      div#scene {
        position: relative;
        width: 100%;
        height: 80%;
        margin: 0px;
        padding: 0px;
      }

      div.box {
        position: absolute;
        width: 100px;
        height: 90px;
        padding-top: 10px;
        text-align: center;
        overflow: hidden;
      }
    </style>
  </head>
  <body>
    <form id="data">
      <input type="button" id="generateButton" value="Generate!">
    </form>

    <div id="scene"></div>

    <script>
      function attachHandler(el, i){
        el.onclick= function() {
          alert("id: " + i);
        }
      }

      function generate() {
        var color = "orange",
            name = "test"
            boxCount = 5,
            scene = document.getElementById("scene");

        for (i = 0; i < boxCount; i++) {
          var x = Math.floor(Math.random() * (scene.offsetWidth-101));
          var y = Math.floor(Math.random() * (scene.offsetHeight-101));
          var div = document.createElement("div");
          div.style.left = x + "px";
          div.style.top = y + "px";
          div.style.backgroundColor = color;
          div.setAttribute("class", "box");
          scene.appendChild(div);
          div.innerHTML = "Box of " + name + "<br />(click me)";
          attachHandler(div, i)
        }
      }

      var generateButton = document.getElementById("generateButton");
      generateButton.onclick = generate;
    </script>
  </body>
</html>

If you have any further questions, just let us know.

What I’m not getting is the stripped down code. Are parts of my code still fine and this is just amended parts needed to add to? Sorry for my misunderstanding, I’m new to coding and new to sites like this to ask questions. Do I need to keep my object constructor and mainly most of the code? I’m just not sure of what stripped down means. I ran the code you provided and nothing happened.

Hi,

No problem. You’ve got to start somewhere and we’re always happy to help people who are willing to learn.

When asking for help from people online, it’s always helpful to post enough code to demonstrate the problem you are having and not more. In your case you had the colour and the text part working. These are not really relevant to the problem you are having, so I stripped them out.

Did you press the “Generate” button. It should generate 5 orange boxes which when clicked will alert their id.
I tested it on Chrome, Firefox and Safari - it worked for me.
If it doesn’t work for you, please let us know which browser and which version you are running.

The rest of your code is fine. You should just understand the principal I have demonstrated here and apply it to what you have.

If this still doesn’t make sense, let me know and I’ll write more.

It’s not putting the value of the id in the alert box. The code other than that works, I figured that part out but, isn’t there supposed to be a global counter value that is pushed into every new Box()?

Lol, you seem to have ignored my advice.

I’m using chrome. I apologize for not responding to the question; /

I’m constantly having to get up mid question or reading responses, I have a 3 week old daughter. No excuses trying to be made, I ran it in chrome, the color, amount of boxes, placement, just not the array value. I was under the impression it needed a counter value that was .push into the object? Thanks again for answering my newbie questions sir, I am trying to immerse myself in js everyday as to get a better grasp on it.

No probs. You gotta love kids.
At least girls normally sleep better than boys :slight_smile:

So, with reference to my code from post 8: in Chrome, when you press “generate”, you see five orange boxes, right?

When you click the boxes, you should see an alert pop up with the index of the respective box. Is this not the case for you?

Nothing happens. So, I tried plugging it into my existing code and I get the alert box with all the demands met but with a blank id. It says the word id but without its numerical value after it.

Did you copy the code from post#8 verbatim?

Just to exclude any typos etc, here is a demo on JSFiddle
Please visit that link, click the generate button (in the bottom right-hand window) and tell me if anything happens.

Yes it worked in js.fiddle. I’ll have to look at it later tonight. I definitely appreciate your patience and time.

1 Like

Im still having problems. Im getting errors in random places now for some reason. Just curious if you are available today for some pointers?

I’m about for the next hour or so, but feel free to post your code and I’ll have a look as soon as I get a chance.

//setting the name keeps giving me errors

window.onload = init;


var boxes = [];

var counter = 0;

function Box(id, name, color, x, y) {
    this.id = id;
    this.name = name;
    this.color = color;
    this.x = x;
    this.y = y;
}

function init() {
    var generateButton = document.getElementById("generateButton");
    generateButton.onclick = generate;
   
    var clearButton = document.getElementById("clearButton");
    clearButton.onclick = clear;

}
 function attachHandler(el, i){
        el.onclick= function() {
          alert("id: " + i);
        }
      }


function generate() {
    var data = document.forms.data;
    var textInput = document.getElementById("name");
    var name = textInput.value;
    if (name == null || name == "") {
        alert("Please give your Amazing Box a name");
        return;
    }
    
    var colorSelect = document.getElementById("color");
    var colorOption = colorSelect.options[colorSelect.selectedIndex];
    var color = colorOption.value;
     if (color == null || color.trim() == "") {
        alert("Pick a color");
        return;
    }
    
     
    // Get count of boxes to create
	var boxCount = 0;
	var radioButtons = document.getElementsByName("amount");
	for(iRadio = 0; iRadio < radioButtons.length; iRadio++)
	{
		if(radioButtons[iRadio].checked)
		{
			boxCount = radioButtons[iRadio].value;
		}
	}

	if(boxCount == null || boxCount == 0)
	{
		alert("Select an amount of boxes to create");
		return;
	}

	// Create boxes
    for (i = 0; i < boxCount; i++) {
		var scene = document.getElementById("scene");
		var x = Math.floor(Math.random() * (scene.offsetWidth-101));
		var y = Math.floor(Math.random() * (scene.offsetHeight-101));
       
          
          
           
            var div = document.createElement("div");
        
            div.style.left = x + "px";
            div.style.top = y + "px";
            div.style.backgroundColor = color;    
            div.setAttribute("class", "box");
            
            scene.appendChild(div);
            div.innerHTML = "Box of " + name + "<br />(click me)";
            attachHandler(div, i)
          }
       }
            
            function attachHandler(div, i) {
               div.onclick = function() {
                alert("You clicked on a box with id " + i + 
                ", named Box of " + name + ", whose color is " + div.style.backgroundColor + 
                " at position " + div.style.top + ", " + div.style.left);
            
       //     }
       //    }
          
           var data = document.getElementById("data");
           data.reset(); 
        
    }
    }
function clear() { 
var sceneDivs = document.querySelectorAll("div#scene div");
        for (var i = 0; i < sceneDivs.length; i++) {
            var scene = document.getElementById("scene");
            var cutList = document.getElementsByTagName("div")[1];
            scene.removeChild(cutList);
       }
     }

Hi,

I’m afraid it doesn’t feel as though you have taken on board anything I wrote in my previous posts.

In the PM I sent to you I explained how to format code when you post it.
Did you get the PM?

You can format code by:

  1. Pasting the code into the editor
  2. Highlighting the code
  3. Hitting the button marked </> in the editor

This is quite vague. Which errors? What do they say?

Also, it would be much appreciated if you could make a code sample that I can run on my PC (like I did in post#8)

If you do that, I’m sure I’ll be able to help.