Calling a Function Inside a Loop

Question

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>


Show source
| javascript   | function   | loops   2017-01-07 09:01 3 Answers

Answers ( 3 )

  1. 2017-01-07 09:01

    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>
    
  2. 2017-01-07 09:01

    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>

  3. 2017-01-07 09:01

    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.

◀ Go back