0

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;
  })
}
Bybnovskiy
  • 105
  • 1
  • 8

2 Answers2

1

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1
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 *= 2;
  })
}

I have tried the above code it's working for me

Aravind
  • 121
  • 1
  • 8