1

I'm trying to use a function directly in the attribute onclick of my button, but i have always an error. Example:

<button onclick="function() { alert('hello'); }">Click me</button>

And the result is:

Uncaught SyntaxError: Unexpected token (

1
  • All you're trying to do is define a function, which wouldn't visibly accomplish anything anyway. Just invoke the code you're trying to invoke: onclick="alert('hello')" If you want to define a function, do that separately in your JavaScript code and just invoke the function in onclick. (Or, even better, attach it as a handler from the JavaScript code so you're not writing in-line JavaScript in your HTML.) Commented Apr 20, 2017 at 15:03

4 Answers 4

4

no need to make it a function, just list the statements:

<button onclick="alert('hello');alert('hello 2');alert('hello 3');">Click me</button>
Sign up to request clarification or add additional context in comments.

2 Comments

It was just an example, I have a complex code with also an ajax call inside the onclick, but the error is always the same
ok, you could update your question to better reflect your special case. Still. Why do you want to use an inline function? there are many other patterns you could use
2

Below code will allow you to add function in your onclick attribute.

Click me

<button onclick="javascript:(function() { alert('hello'); })()">Click me</button>

Comments

0

You should write your code like this.

<button onClick="alert('hello');">Click me</button>

Comments

0

You can do things like that if you want all of this in your html file

    <script>
        function hello(){
    	  alert('hello')
        }
    </script>

    <button id="bait" onClick="hello()">
      Click me
    </button>
    <!-- OR -->
    <!-- <button onclick="javascript:(() => {alert('hello')})()"> -->
    <!-- But it's good for short function only -->

But I think you should use jQuery instead (if you can)



If you want to do so, just add a clickHandler function:

    $("#bait").on("click", () => {
      alert('hello')
    })
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>

<button id="bait">Click me </button>

A bit overkill for a prompt but I suppose you ask this for a trickier function so it'll be easier overall imo

Comments

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.