lundi 3 mai 2021

the value from a function is not comming out

the program is to click a colour and select if you want background or foregground then click 'change color' button it works thats how it should be but while clicking the value from the variable "buttonValue" is not comming out of the function.

the value from button value is not comming out please help.the console says the error is "Uncaught TypeError: Cannot read property 'addEventListener' of null"

html code

<input type="checkbox" name="check" value="background">background</input>
<input type="checkbox" name="check" value="foreground">foreground</input>
<input type="button" value="change color" id='run'>

javascript code

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);
}

var buttonValue;

function change(g){
    buttonValue = g.target.value; 
}   

document.getElementById('run').addEventListener('click',AlertMe);

function AlertMe() {

  document.getElementsByName('check').forEach( (el) =>{
    
    alert(buttonValue);
    if(el.checked === true){
        if((el.value) == "background")
        {
          document.body.style.backgroundColor = buttonValue;
        }
        else if((el.value) == "foreground")
        {
          document.body.style.color = buttonValue;
        }
        
    } 
    
  });
 
}



Aucun commentaire:

Enregistrer un commentaire