Skip to content
Advertisement

Set event listener based on text param from js function

I have a function that will allow me to set a buttons text and onclick property

Both are set as text params

Here is the function:

function assignButton(n,text,onclick){
  var btn = document.getElementById("button" + n)
  btn.innerHTML = text
  btn.onclick = function(){onclick}
}

here is what I call

assignButton(13,"Exit Program","alert('Goodbye')")

The button text is properly assigned but the text that I want to execute is not assigned in the onclick property. It works if I directly type in some code in the function but not when I pass it through as text…

Any ideas on what I could do to get this concept working?

Thanks in advance for your help…

Advertisement

Answer

Pass a function to the assignButton as the onclick parameter, and then you’ll be able to use that to invoke the button’s onclick setter.

function assignButton(n,text,onclick){
  var btn = document.getElementById("button" + n)
  btn.textContent = text;
  btn.onclick = onclick;
}
assignButton(13,"Exit Program",() => alert('Goodbye'))
<button id="button13">button</button>

I’d recommend using .textContent instead of .innerHTML when inserting text – it’s safer and faster.

IDs shouldn’t really be dynamic either. You might consider using classes instead, and then select the nth class.

Advertisement