Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an array of buttons from Javascript array

I want to create a bunch of buttons in the html body based on an array stored in Javascript. Here is my code:

<!DOCTYPE>
<html>
     <head>
           <script>
                var listBrand =['LEXUS','AUDI','MAYBACK','FERRARI','TOYOTA'];   
                //the array
                function printBtn() {
                    for (var i = 0; i < listBrand.length; i++) {
                       var btn = document.createElement("button");
                       var t = document.createTextNode(listBrand[i]);
                       btn.appendChild(t);
                       document.body.appendChild(btn);
                    }
                }
           </script>  
     </head>
     <body>
          <div onload="printBtn();">
          
          </div>
     </body>
</html>

I want to have all 5 buttons LEXUS, AUDI, MAYBACK, FERRARI, and TOYOTA show up in the body when the page loads, but the buttons fail to appear.

Is there anything wrong with my code? Any help and/or explanations are appreciated. Thank you.

like image 736
STEPHEN bui Avatar asked Jan 14 '18 07:01

STEPHEN bui


People also ask

Can I put an array in an array JavaScript?

JavaScript does not provide the multidimensional array natively. However, you can create a multidimensional array by defining an array of elements, where each element is also another array. For this reason, we can say that a JavaScript multidimensional array is an array of arrays.

Can you have an array of objects in JavaScript?

Array Elements Can Be Objects JavaScript variables can be objects. Arrays are special kinds of objects. Because of this, you can have variables of different types in the same Array.

Can you nest arrays in JavaScript?

Nested Array in JavaScript is defined as Array (Outer array) within another array (inner array). An Array can have one or more inner Arrays. These nested array (inner arrays) are under the scope of outer array means we can access these inner array elements based on outer array object name.


2 Answers

The onload event can only be used on the document/body, frames, images, and scripts.

It can be attached to only body and/or each external resource. The div is not an external resource, so the onload event doesn't apply there.

Use following:

<body onload="printBtn();">

Instead of

<div onload="printBtn();">

And you are good to go.

Maybe you should take a look at window.onload vs document.onload here on SO too.

like image 94
Mehdi Dehghani Avatar answered Sep 27 '22 22:09

Mehdi Dehghani


I believe the problem is that the div element doesn't have an onload event.

You should bind the printBtn method to the window.onload event instead.

I created a working jsfiddle for you to see : https://jsfiddle.net/5rq60y0u/1/

like image 31
gillyb Avatar answered Sep 27 '22 23:09

gillyb