-2

I need to write a loop that will iterate the following 2 statements 44 times.

    window.onload = function() {
        var input1 = document.getElementById("alpha1");
        var input2 = document.getElementById("alpha2");
        var input3 = document.getElementById("alpha3");
        input1.onkeypress = alphaFilterKeypress;
        input2.onkeypress = alphaFilterKeypress;
        input3.onkeypress = alphaFilterKeypress;
    };
Ian
  • 50,146
  • 13
  • 101
  • 111
  • What have you tried? [loops](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/for) are quite simple constructs. – Bergi Mar 25 '13 at 15:48

2 Answers2

1

There is no problem in it:

for (var i = 1; i < 45; i++) {
    var input = document.getElementById("alpha" + i);
    input.onkeypress = alphaFilterKeypress;
}
VisioN
  • 143,310
  • 32
  • 282
  • 281
1

Instead of looping through this 44 times, why not delegate the event? attach a single listener, and check if the id matches a given pattern

document.body.addEventlistener('keypress', alphaFilterKeypress, false);

You'll have to change the function definition - adding this check:

function alphaFilterKeypress(e)
{
    e = e || window.event;
    var target = e.target || e.srcElement;
    if (!target.id.match(/alpha[0-9]+/))
    {//don't handle the event
        //event was fired on an element with another (or no) id
        return e;//don't handle it here
    }
    //an element with id alpha[number] fired the event
    //handle the event
}

As you can see from on this previous SO question the type of "key" event you're using is important. Where the keypress event does not pick up on keys like backspace, control etc... you might want to prefer using the keydown event.
Play around with it, and work out which event suites your needs the best

Community
  • 1
  • 1
Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149