Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

this.val() not working for textbox, but $('.selector').val() working

Tags:

jquery

In my code, $("#date") is a textfield with jquery datepicker attached. In the code below, when I select a date, firebug shows this error this.val is not a function

$("#date").change(function(){  
    var mydate = this.val();
    alert(mydate);
});

But when I change this.val() with $("#date").val(), it works perfectly and alerts the selected date. Can anyone point out why this.val() is not working?

EDIT
Sorry, $this was a typo. I actually used this.val(), not $this.val()

like image 798
Sparky Avatar asked Nov 28 '22 03:11

Sparky


2 Answers

this in your event function isn't a jquery object, it's a dom object. Address it as $(this) and it should work for you.

$("#date").change(function(){  
    var mydate = $(this).val();
    alert(mydate);
});
like image 150
Lazarus Avatar answered Nov 30 '22 16:11

Lazarus


You should write

$(this).val();
like image 43
algiecas Avatar answered Nov 30 '22 17:11

algiecas