Reputation: 3158
$("input[type=radio]").change(function(){
alert(this.val());
});
Why this won't work? What I want is that every time a radio button is selected, the page alerts its value.
Upvotes: 3
Views: 354
Reputation: 187252
in jQuery, functions you pass to it's API provide this
as the DOM elements that matched your selector. However, this
is not a jQuery object, it is actually a plain of DOM element. If you want to call jQuery methods on this
, you need to wrap this
in jQuery: $(this)
.
$("input[type=radio]").change(function(){
alert($(this).val());
});
And don't forget to cache it if you use it multiple times to avoid recreating the wrapper over and over.
$("input[type=radio]").change(function(){
var $this = $(this);
$this.addClass('omgitchanged');
alert($this.val());
});
Upvotes: 0
Reputation: 26633
Try this, instead:
$("input[type=radio]").change(function(){
alert($(this).val());
});
You must wrap this
in a jQuery object to use the .val() method.
Upvotes: 0
Reputation: 18099
You need to 'jQuerify' the this
object:
Rather than this.val()
it should be $(this).val()
Upvotes: 1
Reputation: 318698
As @Eonasdan already said, you need to use $(this).val()
.
The reason for this is that this
points to the plain DOM element and .val()
needs a jQuery object.
By the way, you must quote the attribute value in an attribute selector: $("input[type='radio']")
Upvotes: 5
Reputation: 7765
I believe you need to do this:
$("input[type=radio]").change(function(){
alert($(this).val());
});
Upvotes: 10