JQuery/JS newbie here - but so far enjoying the learning experience.
My scenario:
I have multiple buttons like so:
<button id="thumb-1" class="thumbs">click 1</button>
<button id="thumb-2" class="thumbs">click 2</button>
<button id="thumb-3" class="thumbs">click 3</button>
When a user clicks one, I pass it to a custom function via the this
keyword like so:
$('.thumbs').click(function(){
$.fn.myFunc(this);
}
Which will send the jQuery object to the function, i.e the entire button html.
<button id="thumb-x" class="thumbs">click x</button>
Now what I want to do is grab the id of that button and store it on a string variable. Using the following doesn't work of course a html button element has no attr method.
$.fn.myFunc = function(button) {
var id = button.attr('id');
}
Anybody have any simple ideas?
Thanks! - James
JQuery/JS newbie here - but so far enjoying the learning experience.
My scenario:
I have multiple buttons like so:
<button id="thumb-1" class="thumbs">click 1</button>
<button id="thumb-2" class="thumbs">click 2</button>
<button id="thumb-3" class="thumbs">click 3</button>
When a user clicks one, I pass it to a custom function via the this
keyword like so:
$('.thumbs').click(function(){
$.fn.myFunc(this);
}
Which will send the jQuery object to the function, i.e the entire button html.
<button id="thumb-x" class="thumbs">click x</button>
Now what I want to do is grab the id of that button and store it on a string variable. Using the following doesn't work of course a html button element has no attr method.
$.fn.myFunc = function(button) {
var id = button.attr('id');
}
Anybody have any simple ideas?
Thanks! - James
Share Improve this question asked Dec 5, 2012 at 10:32 user896237user8962373 Answers
Reset to default 4If you want to use attr()
then convert button to jquery object or if you want to get id from javascript
object then use button.id
$.fn.myFunc = function(button) {
var id = $(button).attr('id'); // with jquery object
id = button.id; //with javascript object
}
You need to make it a jQuery object before using jQuery function
$.fn.myFunc = function(button) {
var id = $(button).attr('id');
}
if you send "this" from myFunc there is no need to use jquery attr we can access straightly which will be more faster and easier
$(".thumbs").click(function(){
$.fn.myFunc(this);
});
$.fn.myFunc = function(button) {
alert(button.id);
}
Refer the below fiddle
http://jsfiddle/m2Ts5/18/
Thanks