2

Key press event is not working in Mozilla Firefox. I have create a table row dynamically with a text boix in it and that text box has a key press event too.

  var el = document.createElement('input');
           el.type = 'text';
           el.name = 'suggest2';
             el.setAttribute("id",str2); 

             el.setAttribute("onkeypress","additemifenter(this.id)"); 
 cell2.appendChild(el);
row.appendChild(cell2);

In google chrome the function additemifenter(this.id) is called. But in firefox that function is not getting executed. What is the alternate way to do this in firefox?

Smile4ever
  • 3,491
  • 2
  • 26
  • 34
Varada
  • 16,026
  • 13
  • 48
  • 69
  • duplicate: http://stackoverflow.com/questions/95731/why-does-an-onclick-property-set-with-setattribute-fail-to-work-in-ie – davin Jun 04 '11 at 08:54

1 Answers1

6

Maybe the semicolon at the end would help

el.setAttribute("onkeypress","additemifenter(this.id);");

but

why don't you use the standard event handling model:

el.onkeypress = function(event){
// functionality
};

or

el.addEventListener("keypress",function(event){ 
// functionality
},false);

to check the keycode you must use the code:

var code = (event.keyCode) ? event.keyCode : event.which;

if(code == 13){

}
Headshota
  • 21,021
  • 11
  • 61
  • 82
  • Thanks for your help. Actually that function is calling but the checking is not working. The code for the checking in that function isif(window.event.keyCode==13) { addingsecrow2(id); } – Varada Jun 04 '11 at 10:43
  • FYI, could simplify to `var code = event.keyCode || event.which;` – Andi Nov 10 '16 at 18:18