0

I have 10 textbox but i want to apply onkey and blur event on 5 elements.

for(var x=3;x<7;x++){
            document.getElementById("txt_"+x).onclick=function(){
            put_contents(document.getElementById("txt_"+x));
        };
            document.getElementById("txt_"+x).onkeyup = function(){
            validateHexa(document.getElementById("txt_"+x));
        }; 
            document.getElementById("txt_"+x).onblur = function(){
            restore_it(document.getElementById("txt_"+x));
        };
}

after doing this when i click on textbox it is not put_contents take "txt_7" as parameter always. Please suggest the right way. javascript only

Abhinav Parashar
  • 619
  • 4
  • 11
  • 27

1 Answers1

2

You can "detach" the value of x by creating a(nother) closure inside the loop:

for (var x = 3; x < 7; x++) {
    (function(x) {
        document.getElementById("txt_" + x).onclick = function() {
            put_contents(document.getElementById("txt_" + x));
        };
        document.getElementById("txt_" + x).onkeyup = function() {
            validateHexa(document.getElementById("txt_" + x));
        };
        document.getElementById("txt_" + x).onblur = function() {
            restore_it(document.getElementById("txt_" + x));
        };
    })(x);
}

For more information, see How do JavaScript closures work?

Community
  • 1
  • 1
Siguza
  • 21,155
  • 6
  • 52
  • 89