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.
You can definitely send an element's ID to a javascript function.
IDs should be unique within a page, and all elements within a page should have an ID even though it is not necessary. You can add an ID to a new JavaScript Element or a pre-existing HTML Element.
You can get an element by ID with the getElementById() method of the document object. In the Console, get the element and assign it to the demoId variable. Logging demoId to the console will return our entire HTML element.
The id property of the Element interface represents the element's identifier, reflecting the id global attribute. If the id value is not the empty string, it must be unique in a document. The id is often used with getElementById() to retrieve a particular element.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With