0

the background color should change on clicking the button there is one rule the button should be created by matrix as shown bellow.the error is red is the only output comming while clicking any button

var currColor = 5,
  flag = 1;
var colors = ['red', 'blue', 'green', 'yellow', 'black'];
for (var i = 0; i < 5; i++) {
  document.write('<input type="button" onclick="change()" id="btn" value=' + colors[i] + ' style="background-color:' + colors[i] + ' ;"></input>');
}

function change(i) {
  var colorsName = document.getElementById('btn').value;
  document.body.style.backgroundColor = colorsName;
}
Not A Bot
  • 2,220
  • 2
  • 10
  • 24
vishnu kp
  • 5
  • 5
  • 1
    `document.write` is a bad idea: https://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice – yunzen May 03 '21 at 08:15
  • 1
    And using the same id in multiple buttons is also a bad idea, because `.getElementById` can find the first element only. Pass `this` to the function, and read the color from `this.value`. To change the `document.write` see https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Manipulating_documents – Teemu May 03 '21 at 08:22

1 Answers1

0

Every ids that elements have should be unique in the whole document.

So instead working with the document.getElementById() function you should work with the target of the event:

Also you shouldn't use the onclick aatribute rather then use the addEventListener method of the HTML element.

Then document.write shouldn't be used. Use DOM manipulation instead

And if you use a button, I recommend it to be a button element instead of an input[type=button]. But that is debatable.

function change(e){
    var colorsName = e.target.value;
    document.body.style.backgroundColor = colorsName;
}
var currColor = 5, flag = 1;
var colors = ['red', 'blue', 'green', 'yellow', 'black'];
for(var i=0; i<5; i++) {
    var button = document.createElement('button');
    button.type = 'button';
    button.innerText = colors[i];
    button.value = colors[i];
    button.style.backgroundColor = colors[i];
    
    button.addEventListener('click', change)
    document.body.append(button)
}
yunzen
  • 30,001
  • 10
  • 64
  • 93