Getting the id of the pressed button

So, I scratched my head for a long time to get the id of the button pressed, but couldn't get it right. He always brings me back undefined

.

here's a fiddle: http://jsfiddle.net/thinkinbee/mx0rb5cy/

Is there something that I haven't included in my fiddle ?, Is there something wrong in my JS code?

I have addressed the previous questions, but nothing worked. I tried to implement both $(this).attr("id")

and this.id

, but there was no positive result.

Also on a longer stroke all my buttons will dynamically appear. Anything else I need to handle unnecessary?

+3


source to share


5 answers


If the buttons are dynamic you must use document.on.

I figured your fiddle would work like this: http://jsfiddle.net/1ehy66k9/



$(document).on('click', '.ui-btn', function() {
  alert("Clicked with Id "+$(this).attr('id'));
});

      

+6


source


You must pass this

as a parameter:

<a class="ui-btn ui-btn-inline ui-mini" id="check" onclick="chkAlert(this)">click me</a>

      



var chkAlert = function(elem){
    alert("Clicked with Id "+$(elem).attr('id'));
    alert("Clicked with Id "+elem.id);
};

      

JSFiddle Demo .

+2


source


Try it -

HTML -

<a class="ui-btn ui-btn-inline ui-mini" id="check" onclick="chkAlert(this)">click me</a>

      

JavaScript -

var chkAlert = function(t){
    alert("Clicked with Id "+$(t).attr('id'));

};

      

http://jsfiddle.net/mx0rb5cy/6/

+1


source


you need to send the button to the function as a variable this

:

<a class="ui-btn ui-btn-inline ui-mini" id="check" onclick="chkAlert(this)">click me</a>

      

and then get it inside the function (you can call it whatever you want inside the function)

var chkAlert = function(caller){
    alert("Clicked with Id "+caller.id);
};

      

+1


source


you can pass id to the function like onclick = "chkAlert (this.id)" please try like shown

<a class="ui-btn ui-btn-inline ui-mini" id="check" onclick="chkAlert(this.id)">click me</a>


var chkAlert = function(id){
    alert("Clicked with Id "+id);
    alert("Clicked with Id "+id);
};

      

+1


source







All Articles