Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

134
Views
How to run a function with no parameters on an event defined by event listener

I have a function which creates an input element and appends this to another element.

I am trying to make it, so that if an array is used as a parameter of this function, then data from the array is used as the value of the input element. If no array is specified as a parameter, then the input value should be empty.

Here is my code

HTML

<div id="app></div>

Javascript

let app = document.getElementById('app')
let people = [["Adam",10],["Peter",90],["John",30],["Stephen",50]]

for (var key in people) {
  showName(people[key])
}


function showName(pData) {
  let singleName = document.createElement('input')
  
          if (typeof pData !== 'undefined') {
            singleName.value = pData[0]
        }
  
      app.append(singleName)
}


let button = document.createElement('button')
    button.addEventListener('click',showName)
    button.innerHTML = "Add name"
    app.prepend(button)
   

This works fine, I can run the function with a parameter and without a parameter and it works as expected.

When however, I set the function to trigger via an event listener and without a parameter, I can an input with a value of 'undefined', this is not the case if I run the function by writing showName().

This therefore leads me to believe that some kind of parameter is being passed when the event is triggered via an event listener. Is this the case? And if so, how do I make it so that the button creates an input element with no value?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

This therefore leads me to believe that some kind of parameter is being passed when the event is triggered via an event listener. Is this the case?

Yes, your function will get passed the event object, which contains information about the click that took place

And if so, how do I make it so that the button creates an input element with no value?

Instead of passing showName directly into addEventListener, create a new function. That function will ignore the event object, and call showName with no parameters:

button.addEventListener('click', (event) => showName())
// Or:
button.addEventListener('click', () => showName())
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!