Alert ID of current item

I use the following code to warn the id of the current item.

<input type="text" id="desc" name="txtTitle" onclick="fun()">

JQuery

function fun () {
    var currentId = $(this).attr('id');
    alert(currentId);
}

Why does he warn "undefined"? I tried with:

var currentId =$('element').attr('id'); 
// and 
alert($(this).id); 
// and 
alert(this.id);

but he warns undefined

+5
source share
7 answers

Try changing it to:

<input type="text" id="desc" name="txtTitle" onclick="fun.call(this)">

Better associate an event handler with jQuery since you are using it:

$(function() { $('#desc').click(fun); });

The reason your code does not work is because you are calling fun()from the event handler function created by the browser for your onclick attribute. Just by calling such a function, you do not provide the recipient object - nothing to thisbe, that is. If you call it with .call(), you can explicitly do it.

+4
source

$(this) jQuery; fun(). :

$('input#desc').click(function() {
    alert($(this).attr('id'));
});

HTML:

<input type="text" id="desc" name="txtTitle">

onClick="" HTML, , $.click(). JavaScript ( jQuery).

+9

alert($(this).attr('id'));
+2

onclick, . , this .

$("#desc").click(fun)

, , pass this , Pointy.

+1

, :

onclick="fun(this)"

:

function fun(elem)
{
    var currentId = $(elem).attr("id");
}
+1

You can simply use it alert(event.target.id);inside the function called by your element without passing any argument to the function.

+1
source

This is because you were calling thisin a global area.

Without jQuery, you can do as below:

<input type="text" id="desc" name="txtTitle" onclick="fun(this)">

function fun(el) {
    alert(el.id);
}

With jQuery you can do the following:

<input type="text" id="desc" name="txtTitle">

$(function(){
    $('input[type="text"]').click(function(){
        alert(this.id);
    });
});
0
source

All Articles