0

I would like to ask if it is possible to call a function inside a loop using Javascript.

I would like to create a textfield which increments and decrements a button without using the HTML "number" input.

Is there a simpler way to normalize the function by 1 and use a loop instead?

function increment() {
    document.getElementById("myNumber").stepUp(1);
}
function increment2() {
    document.getElementById("myNumber2").stepUp(1);
}
Number: <input type="number" id="myNumber">
<button onclick="increment()">+</button>

Number: <input type="number" id="myNumber2">
<button onclick="increment2()">+</button>
kbunarjo
  • 1,277
  • 2
  • 11
  • 27

3 Answers3

3

How about passing the id as parameter to the function:

function increment(id) {
    document.getElementById(id).stepUp(1);
}

and then:

Number: <input type="number" id="myNumber">
<button onclick="increment('myNumber')">+</button>

Number: <input type="number" id="myNumber2">
<button onclick="increment('myNumber2')">+</button>
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
2

You can pass the id of the input in the function call:

function increment(elem) {
  document.getElementById(elem).stepUp(1);
}
Number:
<input type="number" id="myNumber">
<button onclick="increment('myNumber')">+</button>


Number:
<input type="number" id="myNumber2">
<button onclick="increment('myNumber2')">+</button>
John Bupit
  • 10,406
  • 8
  • 39
  • 75
0

The other answers surely solve the task, but... it's highly not recommended to use 'onclick' and similar attributes to handle the events by JavaScript now (for example, see "Why is using onClick() in HTML a bad practice?").

The recommended way is addEventListener('click', callback), because the code is more maintainable and clear this way.

See https://jsfiddle.net/zrx2xqgg/ as an example for your particular task. The selector of input is passed as attribute to button.

Community
  • 1
  • 1
everyonesdesign
  • 356
  • 2
  • 9