Reputation: 6858
I'm new to Javascript, seems I'm missing something simple here. I just want to return the ID of the button I am clicking but instead I'm getting "undefined."
HTML
<div class="btn-group" id="{{user.get('name')}}">
<button class="btn" id="voteup">^^</button>
<h4>{{user.get('vote')}}</h4>
<button class="btn" id="votedown">vv</button>
</div>
JAVASCRIPT
$(document).ready(".btn").click(function() {
var id = this.id;
alert(id);
)};
Upvotes: 1
Views: 141
Reputation: 1639
If you are using jQuery, you can read the id
attribute like this:
$(this).attr('id');
Upvotes: 0
Reputation: 104775
Try this
$(document).ready(function() {
$(".btn").click(function() {
alert($(this).attr("id"));
});
});
Upvotes: 6
Reputation: 145368
You mixed up the things. $(document).ready()
accepts the handler function which is executed when the DOM tree is fully loaded. The correct solution is:
$(document).ready(function() {
$(".btn").click(function() {
var id = this.id;
alert(id);
});
});
Upvotes: 4
Reputation: 74738
Ofcourse you have error in your javascript:
$(document).ready(".btn").click(function() { //<----here in doc ready handler
var id = this.id;
alert(id);
)}; //<---------------closing of the handler
this should be changed to this:
$(document).ready(function(){
$(".btn").click(function() {
var id = this.id;
alert(id);
});
});
Upvotes: 0
Reputation: 699
I think you should try this way:
jQuery(document).ready(function(){
jQuery('.btn').live('click', function(){
var id = jQuery(this).attr('id');
alert(id);
});
});
Try it and tell us if worked or not (:
Upvotes: 0
Reputation: 7055
Correct way to bind click listener is
$(function(){
$(document).on("click",".btn",function(e){
alert($(this).prop("id"));
});
});
Upvotes: 0