Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to program HTML input onKeyPress event with javaScript?

I´m trying to program html input onkeypress event from javascript but it doesn´t work, but I can program atributes like size or type.

var element3 = document.createElement("input");
element3.type = "text"
element3.size = "6"   
element3.onkeypress= "return isNumberKeyDecimal(event)"

Is that possible?

like image 788
Mikelon85 Avatar asked Oct 22 '12 08:10

Mikelon85


3 Answers

The onkeypress property accepts a function, not a string.

element3.onkeypress = isNumberKeyDecimal;

But also take a look at the addEventListener function for the preferred approach to dealing with event listener functions.

In particular, you may wish to look at event delegation, which would allow you to have a single event listener on a container element rather than having to bind it to each input you create.

like image 74
Quentin Avatar answered Sep 28 '22 07:09

Quentin


element3.setAttribute("onkeypress", "return isNumberKeyDecimal(event)");
like image 31
Russell Gutierrez Avatar answered Sep 28 '22 08:09

Russell Gutierrez


element3.setAttribute("onkeypress", "return isNumberKeyDecimal(event)");

Mozilla reference here

like image 24
user1888581 Avatar answered Sep 28 '22 07:09

user1888581