Vlada
Vlada

Reputation: 145

Logging values from currently focused textarea

Let us assume that I have many textarea elements on my page, and my goal is to log the value of current textarea element that I am typing on.

I have managed to write the code that does just that, but the problem is that when type text in one textarea, and then switch to another and type in that for a while, when I come back to the first one, I get two .keyup() methods attached to that element. So I get two logs of that textarea value.

$( "body" ).click( function( event ) {
  let element = event.target
  if( element.nodeName === "TEXTAREA" ){
    if($(element).focus()){
      $(element).keyup(function(){      
        console.log(element.value)   
      })
    }else {
      $(element).unbind( 'keyup' )
    }  
  }
});

What do I need to do to remove that method stacking?

Upvotes: 1

Views: 694

Answers (1)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

You should never attach event inside another event because when the first fired the one inside will be attached another time and so on.

I suggest attaching the input event directly to the textarea's instead of keyup and nested events, so with the helps of this keyword you will get the current changed textarea element, like :

$("textarea").on('input', function(event) {
  console.log($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<textarea></textarea>
<br>
<textarea></textarea>
<br>
<textarea></textarea>

Upvotes: 3

Related Questions