[javascript] 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 question is related to javascript html

The answer is


The problem for me was as simple as just not knowing Javascript well. I was trying to pass the name of the id using double quotes, when I should have been using single. And it worked fine.

This worked:

validateSelectizeDropdown('#PartCondition')

This did not:

validateSelectizeDropdown("#PartCondition")

And the function:

    function validateSelectizeDropdown(name) {
    if ($(name).val() === "") {
         //do something
    }
}

Check this: http://jsfiddle.net/h7kRt/1/,

you should change in jsfiddle on top-left to No-wrap in <head>

Your code looks good and it will work inside a normal page. In jsfiddle your function was being defined inside a load handler and thus is in a different scope. By changing to No-wrap you have it in the global scope and can use it as you wanted.


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>

you can use this.

<html>
    <head>
        <title>Demo</title>
        <script>
            function passBtnID(id) {
                alert("You Pressed:  " + id);
            }
        </script>
    </head>
    <body>
        <button id="mybtn1" onclick="passBtnID('mybtn1')">Press me</button><br><br>
        <button id="mybtn2" onclick="passBtnID('mybtn2')">Press me</button>
    </body>
</html>