Reputation: 2168
In the snippet below I use $(this)
to refer to the element in which the function is being called from. I know it is not correct because I printed out the values and it gave me 'undefined'. How do I refer to the input element?
$(function() {
$( ".datepicker" ).datepicker({
onSelect: function (date, obj){
if(confirm('Is this correct?: '+ date )) {
$.post('edit.php', {
"row": $(this).data('id'),
"date":date,
"field":$(this).name,
"ajax":'true'
});
}
}
});
});
Here is the html element:
<input
name="appvAcadVp"
data-id="someid"
class="datepicker" size="10"
type="text"
placeholder="someholder"
>
Upvotes: 2
Views: 350
Reputation: 490667
jQuery sets this
itself, generally to point to the current element.
Otherwise, in JavaScript...
var a = {
b: function() {
// `this` is `a`
}
}
a.b();
Except, where the property becomes assigned to a variable. Observe...
var c = a.b;
c(); // the `this` will point to `window`
var a = function() {
// `this` is `window`
}
a();
var C = function() {
// `this` is `c`
}
var c = new C();
Note that if your forgot to instantiate with new
, JavaScript will assign those properties to the global object (window
in a browser).
// In global scope `this` is `window`
var d = this;
call()
or apply()
You can also set this
explicitly with call()
and apply()
function methods.
Thanks for the explanation of 'this' but I still dont understand why the reference isn't working in my code
My apologies.
$(this).name
won't work as this
is now a jQuery object and has only a few properties (none of which are name
).
Either use $(this).attr('name')
or drop wrapping this
with the jQuery object and just access this.name
.
Upvotes: 8
Reputation: 50215
That's what the obj
parameter is for in the onSelect function, so you'd reference $(obj)
. Just for reference, this
will refer to the associated input field.
For reference, see: http://jqueryui.com/demos/datepicker/ > Events > onSelect
Upvotes: 1