Bybnovskiy Bybnovskiy - 1 month ago 8
HTML Question

Change value and add event listener

I'm generating some inputs, and adding event listener to each of them, how to increase the value * 2, when I'm focusing on each them ?

Here what I've got:

for (var i = 0; i < 3; i++) {
var input = document.createElement("input");
document.body.appendChild(input);
random = Math.floor((Math.random() * 100) + 1);
this.input.value = random;
input.addEventListener('focus', function(e) {
this.value += random * 2;
})
}

Answer

The value of an input is always a string. + does string concatenation when either of its operands is a string.

So you'll want to parse value to use it as a number:

for (var i = 0; i < 3; i++) {
  var input = document.createElement("input");
  document.body.appendChild(input);
  random = Math.floor((Math.random() * 100) + 1);
  this.input.value = random;
  input.addEventListener('focus', function(e) {
    this.value = +this.value + random * 2;
  })
}

In that, I'm using + to coerce this.value to a number. Other options are parseInt, parseFloat, and Number.

However, you've said

how to increase the value * 2, when I'm focusing on each them

That's not what your code tried to do. Your code tried to add random * 2 to the value. To just double it, double it:

for (var i = 0; i < 3; i++) {
  var input = document.createElement("input");
  document.body.appendChild(input);
  random = Math.floor((Math.random() * 100) + 1);
  this.input.value = random;
  input.addEventListener('focus', function(e) {
    this.value = +this.value * 2;
  })
}

There I'm still using + for emphasis, but * will coerce its operands to number, so this.value *= 2 would also work.