Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent key UP & DOWN behavior in HTML Input Fields?

I know there are similar questions on stackoverflow, but none of them I think has working solution. So when you type key UP or Down when you have focus on an HTML input field, the cursor automatically moves to the front/end of the input value.

(You can check this with the Top-right Search box on the stackoverflow site).

I want to remove this!!

I tried the following code, but didn't work:

$(document).on("keydown", "#input_field", function(event) {
    if(event.which==38 || event.which==40){
        event.preventDefault();
    }
});

Any solution for this..?

like image 730
user2492270 Avatar asked Aug 17 '13 16:08

user2492270


1 Answers

I don't see the point in preventing a fairly useful behavior, but this works for me with the SO search box:

$(document).on("keydown keyup", "#search input", function(event) { 
    if(event.which==38 || event.which==40){
        event.preventDefault();
    }
});

This code targets both keyup and keydown events.

like image 178
MasterAM Avatar answered Oct 11 '22 22:10

MasterAM