gaetanm
gaetanm

Reputation: 1404

setTimeout() and $(this) produce a strange bug

I'm just trying to simulate live typing with this function:

$('#expenseAccordion').on('keypress', '.netAmount input', function() {
    setTimeout(function() {
        $(this).closest('.accordion-group').find('.amount input').val($(this).val());
    }, 0);
});

This doesn't work and produces this strange bug:

Uncaught TypeError: Cannot call method 'toLowerCase' of undefined

The jQuery line where there is the problem (l 4245):

hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];

If I delete all $(this) from the function and try thing like that:

$('#expenseAccordion').on('keypress', '.netAmount input', function() {
setTimeout(function() {
    $('.amount input').val(4);
}, 0);

});

It works, but I really need to get the current element where the event occurs because I have more than one input.

Upvotes: 1

Views: 665

Answers (3)

gabitzish
gabitzish

Reputation: 9691

The first this points to your timeout, so any selection you are making it's going to be null.

Here is how I would do it:

$('#expenseAccordion').on('keypress', '.netAmount input', function() {
    var self = this;
    setTimeout(function() {
        $(self ).closest('.accordion-group').find('.amount input').val($(self).val());
    }, 0);
});

Upvotes: 0

xdazz
xdazz

Reputation: 160883

Another common way is just create a local variable to hold it.

$('#expenseAccordion').on('keypress', '.netAmount input', function() {
    var $this = $(this);
    setTimeout(function() {
       $this.closest('.accordion-group').find('.amount input').val($this.val());
    }, 0);
 });

Upvotes: 3

Arun P Johny
Arun P Johny

Reputation: 388406

this inside settimeout does not point to the expenseAccordion element, you can use $.proxy() to pass a custom execution context to the callback function

setTimeout($.proxy(function() {
    $(this).closest('.accordion-group').find('.amount input').val($(this).val());
}, this), 0);

Upvotes: 10

Related Questions