最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

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?

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?

Share Improve this question edited Sep 4, 2018 at 8:32 Mikelon85 asked Oct 22, 2012 at 8:40 Mikelon85Mikelon85 4321 gold badge16 silver badges31 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 8

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.

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

Mozilla reference here

It should be set as a function not a string.

element3.onkeypress = function(event){return isNumberKeyDecimal(event)}
发布评论

评论列表(0)

  1. 暂无评论