开发者

How can i Assign onkeypress-function to dynamically created input-boxes in javascript?

How can i Assign onkeypress-function to dynamically created input-boxes in javascript ?

You can find my source code here: http://goo.gl/9BHSt

var cell2 = row.insertCell(1);
var el = document.createElement('input');
el.type = 'text';
el.size = "3";
el.name = 'txtUnit' + iteration;
el.id = 'txtUnit' + iteration;
el.onKeyPress = "return checkIt(event)";                       
cell2.appendChild(el);   
el.type = 'text';
el.size = "3";
el.name = 't开发者_开发问答xtUnit' + iteration;
el.id = 'txtUnit' + iteration;
el.onKeyPress = "return checkIt(event)";                       
cell2.appendChild(el);  

But el.onKeyPress = "return checkIt(event)"; is not working . Why ?


use this :

el.onkeypress = 
   function(event)
   {
      //write your method body
   };

or

el.onkeypress = KeyPressHandler;
function KeyPressHandler(event)
{
   //write your method body
}

EDIT

You have provided wrong argument. see this :

function KeyPressHandler(event)
{
   evt = (evt) ? evt : window.event
   var charCode = (evt.which) ? evt.which : evt.keyCode
   if (charCode > 31 && (charCode < 48 || charCode > 57)) {
      status = "This field accepts numbers only."
      return false;
   }
   status = ""
   return true;
}   

you should change parameter name to evt

function KeyPressHandler(evt)
{
   evt = (evt) ? evt : window.event
   var charCode = (evt.which) ? evt.which : evt.keyCode
   if (charCode > 31 && (charCode < 48 || charCode > 57)) {
      status = "This field accepts numbers only."
      return false;
   }
   status = ""
   return true;
} 

I tested, and It worked fine.


You'll be better off using jQuery. It has a live function which allows to attach events to dynamically added elements.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜