Storm
Storm

Reputation: 73

How write function in onclick button attribut

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 (

Upvotes: 1

Views: 16990

Answers (4)

Manu
Manu

Reputation: 396

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

Upvotes: 0

Kumar Nitesh
Kumar Nitesh

Reputation: 1652

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

Click me

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

Upvotes: 2

Damien
Damien

Reputation: 1620

You should write your code like this.

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

Upvotes: 0

user5328504
user5328504

Reputation: 764

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

<button onclick="alert('hello');alert('hello 2');alert('hello 3');">Click me</button>

Upvotes: 4

Related Questions