-3

If I have an input with class 'textInputs' and have a paste function for those elements, I need to nest a setTimeout function inside the paste event function, but then how can I define this inside the timeout function? The code below does not work as this is not defined inside the setTimeout function. Thank you.

$('.textInputs').on('paste',function() { 

       var element = this;

       window.setTimeout(function() {  
       newstr = element.value.replace(/\n/g, '');  

       $(this).val(newstr);

   },100);  
}); 
user2014429
  • 2,497
  • 10
  • 35
  • 49

3 Answers3

5

Just used the cached one itself, this in the setTimeout callback points to the global context not the element.

$('.textInputs').on('paste',function() { 

       var element = this;
          window.setTimeout(function() {  
          newstr = element.value.replace(/\n/g, '');  
          $(element).val(newstr); //<-- Here
          //or just
          //element.value = element.value.replace(/\n/g, '');
   },100);  
}); 

You can simplify this using the .val( function(index, value) ) syntax:

$('.textInputs').on('paste',function() { 
       var $element = $(this);
       window.setTimeout(function() { 
          $element.val(function(_, currVal){ 
             return currVal.replace(/\n/g, '');
          }); 
    },100);  
}); 
PSL
  • 123,204
  • 21
  • 253
  • 243
2

perhaps you mean this ?

$('.textInputs').on('paste',function() { 

       var element = this;

       window.setTimeout(function() {  
       newstr = element.value.replace(/\n/g, '');  

       $(element ).val(newstr);

   },100);  
}); 
Rainer Plumer
  • 3,693
  • 2
  • 24
  • 42
1

You were referencing this instead of your element.

  var element = $(this);
   window.setTimeout(function() {  
       newstr = element.value.replace(/\n/g, '');  
       element.val(newstr);
   },100);  
Trevor
  • 16,080
  • 9
  • 52
  • 83