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

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

programmeradmin11浏览0评论

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/

发布评论

评论列表(0)

  1. 暂无评论