最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

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

matteradmin6PV0评论

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/

Post a comment

comment list (0)

  1. No comments so far