最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to prevent key UP & DOWN behavior in HTML Input Fields? - Stack Overflow

programmeradmin7浏览0评论

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..?

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..?

Share Improve this question edited Aug 17, 2013 at 16:24 j08691 208k32 gold badges269 silver badges280 bronze badges asked Aug 17, 2013 at 16:22 user2492270user2492270 2,2856 gold badges43 silver badges56 bronze badges 3
  • 1 why do you want to do that? – Swaroop Nagendra Commented Aug 17, 2013 at 16:27
  • @SwaroopNagendra I'm writing a browser game that makes use of the arrow keys. Preventing the default browser behaviour is crucial... for example. – Foxinni Commented Jan 21, 2014 at 8:28
  • Did the answer solve the issue? – MasterAM Commented Oct 12, 2016 at 11:48
Add a ment  | 

1 Answer 1

Reset to default 7

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.

发布评论

评论列表(0)

  1. 暂无评论