How to access the id of the button who called a Javascript function using $(this)?

I am new to Javascript. I have set a couple of buttons on a page, like this:

<div id='MID_1_4'>
    <div id="login">logout</div>
    <button type="button" id="logout" onclick="loadXMLDoc2()">Logout</button>
</div>
...

I want to extract the id of the button who called loadXMLDoc2(). This method is defined as following:

function loadXMLDoc2() {

    var retr = $(this).attr("id");
    document.getElementById("L1_LEFT").innerHTML
        = retr;

}

Yet, L1_LEFT is set to undefined when I click on buttons. I thought $(this) meant "the current HTML element". If it is not the button then what is it? And how can I extract the button's id?

Upvotes: 0

Views: 302

Answers (2)

Sinthia V
Sinthia V

Reputation: 2093

Yes indeed, the variable this refers to the target element of an event handler. I think you are over complicating it, however. Try

var retr = this.id;

to obtain your id. KISS!!

Upvotes: 1

Esailija
Esailija

Reputation: 140228

this refers to window (the global object) inside the function, this refers to the element in the onclick handler.

while it's bad approach to do javascript in html, try this:

<div id='MID_1_4'>
    <div id="login">logout</div>
    <button type="button" id="logout" onclick="loadXMLDoc2(this)">Logout</button>
</div>

function loadXMLDoc2(elm) {

    var retr = elm.id;
    document.getElementById("L1_LEFT").innerHTML
    = retr;

}

A better approach is to separate HTML and javascript:

<div id='MID_1_4'>
    <div id="login">logout</div>
    <button type="button" id="logout">Logout</button>
</div>

(Somewhere in js file )

function loadXMLDoc2(elm) {

    var retr = elm.id;
    document.getElementById("L1_LEFT").innerHTML = retr;

}

$( document ).ready( function(){
//This function is executed after all elements on the page are ready to be manipulated

    $( "#logout" ).bind( "click",
        function(){
        loadXMLDoc2( this );
        }
    );
});

Upvotes: 2

Related Questions