homepage Welcome to WebmasterWorld Guest from
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Pubcon Platinum Sponsor 2014
Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

prevent default action of keys up and down in input field
i need to prevent the default action when pressing eighter up or down

5+ Year Member

Msg#: 4382017 posted 11:50 am on Nov 1, 2011 (gmt 0)

I have a search input field and I'm using javascript to move through the search suggestions, the problem i'm facing is that every time someone presses up or down the text cursor moves to the first/last character in the input field, I tried using event.preventDefault with no succes.

Here is a test page for it:

<input type="text">
<script type="text/javascript">
document.onkeyup = KeyCheck;
function KeyCheck(evt)
var evt=(evt)?evt:event;
var KeyID = evt.keyCode;
case 40:
alert("Pressed DOWN");
case 38:
alert("Pressed UP");

Thank you in advance for any help on my issue.



WebmasterWorld Senior Member fotiman us a WebmasterWorld Top Contributor of All Time 5+ Year Member Top Contributors Of The Month

Msg#: 4382017 posted 8:45 pm on Nov 4, 2011 (gmt 0)

I suspect the problem may be where you are attaching your event handler... at the document level. Events "bubble" up the DOM tree, so by the time your KeyCheck method is being called, the event handler at the INPUT element has already completed (including the default action). I suspect that if you attached this to the onkeyup event handler of your INPUT element instead of the document, then it might do what you expect.


5+ Year Member

Msg#: 4382017 posted 9:58 pm on Nov 4, 2011 (gmt 0)

Thank you for your reply, in the meanwhile I managed to solve my problem. You are right, it was the event handler, but I didn't bind it to the onkeyup of the INPUT, I called keydown on the INPUT and did preventDefault() there just for the 2 keys. Works great now.

Global Options:
 top home search open messages active posts  

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved