-1

I have written a piece of code. On clicking on a button corresponding function should be called. While the logic works for funcB and funcD i.e. they get invoked on clicking FieldB and FieldD. FunctionA gets called for some reason on page load.Can someone explain what am I doing wrong here?Happy to share additional code if doesn't make sense.

function funcA(array){alert("Invoked");}

function init() {
    loadData();
    document.getElementById("FieldA").onclick = funcA(array1);
    document.getElementById("FieldB").onclick = funcB;
    document.getElementById("FieldC").onclick = funcA(array2);
    document.getElementById("FieldD").onclick = funcD;
}

window.onload = init;
misguided
  • 3,699
  • 21
  • 54
  • 96

2 Answers2

3

When ever you call a function it returns a value. funcA(array1) doesn't refer to function variable but it will be the value returned from the function funcA which is undefined in this case. If you want to pass some arguments then use wrapper function.

document.getElementById("FieldA").onclick =() => funcA(array1);

A better way is to use addEventListener

document.getElementById("FieldA").addEventListener('click',e => funcA(array1))
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
0

you are executing the funcA on onload, instead you can add a wrapper function over the funcA eg:

document.getElementById("FieldA").onclick = function() {
  funcA(array1);
}
Joseph
  • 682
  • 5
  • 17