Welcome to WebmasterWorld Guest from 54.166.46.226

Forum Moderators: open

Message Too Old, No Replies

prevent default action of keys up and down in input field

i need to prevent the default action when pressing eighter up or down

   
11:50 am on Nov 1, 2011 (gmt 0)

5+ Year Member



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.
8:45 pm on Nov 4, 2011 (gmt 0)

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



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.
9:58 pm on Nov 4, 2011 (gmt 0)

5+ Year Member



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.