0

I'm trying to get the value of an input field after pasting text into it. How come when I access $(this) here, that it's referencing m.fn.init [Window]?

  $("#contract-billing-card-number").on('paste', function() {
        setTimeout(function() {
            console.log($(this)); // returning window, expecting #contract-billing-card-number
            console.log($(this).val()); // trying to get value
        }, 1);
  });
Michael
  • 403
  • 1
  • 9
  • 28
  • 1
    because `setTimeout` is a window function - you are inside the setTimeout, thus this = window. Try outside the setTimeout and you should see what you're expecting – treyBake Aug 29 '18 at 16:09
  • You'd need to bind `this` to the function callback in setTimeout – Derek Pollard Aug 29 '18 at 16:09
  • Or, even better, use an arrow function – Derek Pollard Aug 29 '18 at 16:10
  • 1
    Because `setTimeout` calls your callback without setting any particular this value and your code is running in "loose" mode. (If you were using `"use strict";`, `this` would be `undefined`.) So `this` defaults to the global object, which is window in browsers. See the linked question's answers for what to do about it (basically: use an arrow function, or do `var element = this;` before calling `setTimeout` and use `element` within the callback). – T.J. Crowder Aug 29 '18 at 16:13

0 Answers0