-1

Let's say I have several textareas, and I want to add event listener to each textarea. When I type inside a textarea, I need to console the value typed inside it. I just can't figure out how to refer "this" to each textarea called in looping when being added event listener. The code below results in "undefined" in the browser console. Maybe you can set it right. Appricated the help. Thank you very much.

window.addEventListener("load", function(){
    var char_max_inputs = document.querySelectorAll('.char_max');
    for (var i = 0; i < char_max_inputs.length; i++){
        var max_char = char_max_inputs[i].getAttribute("max_char");
        var counter_id = char_max_inputs[i].getAttribute("counter_id");     
        char_max_inputs[i].addEventListener("keyup", function(){count_char(counter_id, max_char);}, false);
    }
});

function count_char(counter_id, max_char) {
    console.log(this.value);
}
  • Possible duplicate of [addEventListener using for loop and passing values](https://stackoverflow.com/questions/19586137/addeventlistener-using-for-loop-and-passing-values) – Allen Jun 12 '17 at 17:46

1 Answers1

-1

You can solve it like this by using Function.prototype.bind

window.addEventListener("load", function() {
  var char_max_inputs = document.querySelectorAll('.char_max');
  for (var i = 0; i < char_max_inputs.length; i++) {
    var max_char = char_max_inputs[i].getAttribute("max_char");
    var counter_id = char_max_inputs[i].getAttribute("counter_id");
    char_max_inputs[i].addEventListener("keyup", count_char.bind(char_max_inputs[i], counter_id, max_char), false);
  }
});

function count_char(counter_id, max_char) {
  console.log(this.value);
}
<textarea class="char_max"></textarea>
<textarea class="char_max"></textarea>
<textarea class="char_max"></textarea>

this can be very confusing in JavaScript, if not read about properly. An excellent resource to understand it is here

UPDATE

As pointed out in the comments, the example using call and bind together was incomplete. Removing it.

maazadeeb
  • 5,922
  • 2
  • 27
  • 40