CamilleTea
CamilleTea

Reputation: 9

How to pass id to a function?

JavaScript:

function executeOnclick() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (xhttp.readyState == 4 && xhttp.status == 200) { 
            myFunction(xhttp);
        }
    };

    xhttp.open("GET","http://try.com/students/search.php?stud_id=?" +x , true);
    xhttp.send();
}   

function myFunction(obj){
    var xmlDoc = obj.responseText;
    var x = xmlDoc.getElementsByTagName("id");

    document.getElementById("demo").innerHTML = xhttp.responseText;
}   

HTML:

<img id="1210" onclick="executeOnclick()" onload="myElement(this);" 
     class="Cpictures" src="1.jpg" width=50px height=75px alt="Robert" />

This code doesn't work. I want that when I call the myFunction function, I get the Id of the image and pass it to my API. How do I do that?

Upvotes: 0

Views: 229

Answers (1)

Redmega
Redmega

Reputation: 683

The issue is that the function myElement() doesn't accept any parameters. Passing this passes a reference of the object from which it's called (specifically, in this case, an instance of HTMLImageElement). But your function isn't looking for anything at all.

Changing your function from:

function myElement(){
    var getID = document.getElementById(this.id);
}   

to:

function myElement(obj){
    //Insert code you want here. I printed the id to console for example.
    console.log(obj.id);
}

Will allow you to access the object's id (And any other part of the id you want to use).

JSFiddle

Upvotes: 2

Related Questions