6

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?

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1, because +3 is not possible: +1 for addEventListener (attachEvent for older IE's), +1 for not using a wrapper function, but assigning the handler directly and +1 for suggesting delegation
3
element3.setAttribute("onkeypress", "return isNumberKeyDecimal(event)");

1 Comment

Will that work? Do browsers (other than IE with its global event object) create an event variable when you set the attribute as a string?
2
element3.setAttribute("onkeypress", "return isNumberKeyDecimal(event)");

Mozilla reference here

Comments

1

It should be set as a function not a string.

element3.onkeypress = function(event){return isNumberKeyDecimal(event)}

1 Comment

Or, you could write this code as element3.onkeypress = isNumberKeyDecimal;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.