-2

I want to call a function Encode when a button is clicked.

My code is:

let data = document.getElementById("d1");
let encode = document.getElementById("btnEncode");
let encrypt = document.getElementById("btnEncrypt");
let display = document.getElementById("i1");
let form = document.getElementById("form1");

function Encode() {
  let l = data.value;
  console.log(l);
  l = btoa(l);
  display.value = l;
  console.log(l);
}

When I use encode.onclick=Encode(); the value of l is empty in Encode() and when I use encode.addEventListener("click", Encode);, it works fine.

Can anyone tell me the reason?

Amit Kumar
  • 9
  • 1
  • 2

1 Answers1

1

encode.onclick() tries to call onclick immediately. This gives you a value. (Or it throws an exception because it is undefined instead of a function you can call).

=Encode(); then calls Encode immediately and tries to assign its return value to the LHS. Since the LFS is a value (and not a property or a variable), this throws an error.

The correct (albeit ancient) syntax would be encode.onclick = Encode.

The modern approach is addEventListener. Stick to that.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335