BattleGuard
BattleGuard

Reputation: 13

Calling a Function Inside a Loop

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>

Upvotes: 0

Views: 986

Answers (3)

everyonesdesign
everyonesdesign

Reputation: 364

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.

Upvotes: 0

John Bupit
John Bupit

Reputation: 10618

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>

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

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>

Upvotes: 3

Related Questions