Pass element ID to Javascript function

I have seen many threads related to my question title.

Here is HTML Codes :

<button id="button1" class="MetroBtn" onClick="myFunc(this.id);">Btn1</button>
<button id="button2" class="MetroBtn" onClick="myFunc(this.id);">Btn2</button>
<button id="button3" class="MetroBtn" onClick="myFunc(this.id);">Btn3</button>
<button id="button4" class="MetroBtn" onClick="myFunc(this.id);">Btn4</button>

And a very simple JS function is here :

function myFunc(id){
        alert(id);
}

You can see in JsFiddle.

The problem is :

I have no idea, maybe doesn't pass this.id to myFunc function, or some problem else.

What's the problem ?

Any help would be appreciated.


This'll work:

<!DOCTYPE HTML>
<html>
    <head>
        <script type="text/javascript">
            function myFunc(id)
            {
                alert(id);
            }
        </script>
    </head>

    <body>
        <button id="button1" class="MetroBtn" onClick="myFunc(this.id);">Btn1</button>
        <button id="button2" class="MetroBtn" onClick="myFunc(this.id);">Btn2</button>
        <button id="button3" class="MetroBtn" onClick="myFunc(this.id);">Btn3</button>
        <button id="button4" class="MetroBtn" onClick="myFunc(this.id);">Btn4</button>
    </body>
</html>

In jsFiddle by default the code you type into the script block is wrapped in a function executed on window.onload:

<script type='text/javascript'>//<![CDATA[ 
    window.onload = function () {
        function myFunc(id){
            alert(id);     
        }
    }
//]]>  
</script>

Because of this, your function myFunc is not in the global scope so is not available to your html buttons. By changing the option to No-wrap in <head> as Sergio suggests your code isn't wrapped:

<script type='text/javascript'>//<![CDATA[ 
    function myFunc(id){
       alert(id);     
    }
//]]>  
</script>

and so the function is in the global scope and available to your html buttons.