javascript - Run a function at the first keypress event on an input - Stack Overflow

I have an input element with an onkeypress event that runs a function, change(). The problem is that th

I have an input element with an onkeypress event that runs a function, change(). The problem is that the function doesn't run for the very first keypress. For example, I have to type 55 instead of 5 to get the function to update, and the value it takes is 5. Somehow, it doesn't recognize the most recent keypress. I tried adding other events, such as onfocus and onselect, to no avail. Here is the code for the input:

<input id="x" type="text" size="1" maxlength="2" onkeypress="change()" onfocus="change()" onselect="change()" onblur="change()" onchange="change()"></input>

I have an input element with an onkeypress event that runs a function, change(). The problem is that the function doesn't run for the very first keypress. For example, I have to type 55 instead of 5 to get the function to update, and the value it takes is 5. Somehow, it doesn't recognize the most recent keypress. I tried adding other events, such as onfocus and onselect, to no avail. Here is the code for the input:

<input id="x" type="text" size="1" maxlength="2" onkeypress="change()" onfocus="change()" onselect="change()" onblur="change()" onchange="change()"></input>

Share Improve this question asked May 14, 2013 at 22:12 IanIan 6,1846 gold badges46 silver badges76 bronze badges 2
  • Would using onkeyup instead work? Also, what does the change() function do and how do you know it is not running it the first time? – Nope Commented May 14, 2013 at 22:15
  • Yes! Thanks, I had no idea that existed. Please post it as an answer so I can select it. – Ian Commented May 14, 2013 at 22:19
Add a ment  | 

3 Answers 3

Reset to default 2

I think the issue might be that the onkeypress event triggers before the value is inserted.

If you want to capture the value after the key has been pressed you could use the onkeyup event instead and see if that works better.

you might to try this event

onKeyUp="change()"

link no longer valid

I guess it is because the value is just set after you release the key. When I try it with onkeyup its working

http://jsfiddle/j8B8b/2/

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745650515a4638236.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信