[Solved] How to connecting the function, createElement and random? [closed]


As per my understanding, you are trying to create ‘n’ no.of random buttons as of in the innerHTML of #demo.

If so you need to loop it. Try this

function myFunction() {
    var num = 5;
    document.getElementById("demo").innerHTML = Math.floor(Math.random() * num)
    var noOfButtons = document.getElementById("demo").innerHTML;
    for (var i = 0; i < noOfButtons; i++) {
        var box = document.createElement("BUTTON");
        document.body.appendChild(box);
    }
}

JSfiddle

From your comments:

1) No display of numbers, so remove the innerHTML of #demo element.

2) Reset the button count for each button invoke.

Whenever you invoke the click event, better reset the value to empty like below

document.getElementById('demo').innerHTML = '';

3) You need to append the child (box) to the #demo element instead of body like below

document.getElementById('demo').appendChild(box);

Finally, your code should look like this.

function myFunction() {
    document.getElementById('demo').innerHTML = '';
    var num = 5;
    var noOfButtons = Math.floor(Math.random() * num);
    console.log(noOfButtons);
    for (var i = 0; i < noOfButtons; i++) {
        var box = document.createElement("BUTTON");
        document.getElementById('demo').appendChild(box);
    }
}

Updated JSFiddle

Hope you got some idea.

9

solved How to connecting the function, createElement and random? [closed]