1

How do I activate existing HTML button, say running the onClick function in specific button?

When using document.getElementById("Button ID").onclick I get the function with the parameters, like the following example. but how do I run the function?

Example, the document.getElementById("Button ID") result is:

ƒ onclick(event) {calculate('ABC',1,8)}

In this example, how do I run calculate('ABC',1,8) function from javascript?

1
  • Couldn't you do document.getElementById("Button ID").onclick(); ? Commented Feb 24, 2018 at 23:39

4 Answers 4

1

You can call the click method on the button element.

document.getElementById("Button ID").click()
Sign up to request clarification or add additional context in comments.

Comments

1

You simply call the click() function on the same element.

document.getElementById("Button ID").click()

This will trigger the onclick handler.

Comments

1
  • A function is called using parenthesis (), i.e: fn().
  • What you're getting is the declaration of that function.

You need to call it as follow:

document.getElementById("Button ID").click();

I recommend you to read about addEventListener and Event click.

Comments

0
const calculate = (p1, p2, p3) => {
    return p2 + p3
}

document.getElementById("Button ID").onclick = () => {
    const res = calculate('ABC',1,8)
    alert (res)
}

1 Comment

Thanks to take time to answer the question. Though this can be an answer, is better if you format the code and explain what you do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.