homepage Welcome to WebmasterWorld Guest from 54.234.128.25
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
jaruba




msg:4382019
 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;
switch(KeyID)
{
case 40:
alert("Pressed DOWN");
break;
case 38:
alert("Pressed UP");
break;
}
}
</script>


Thank you in advance for any help on my issue.

 

Fotiman




msg:4383654
 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.

jaruba




msg:4383684
 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