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

javascript - How do I trigger ESC button to clear text entered in text box? - Stack Overflow

programmeradmin4浏览0评论
   <input type="text" id="search" size="25" autocomplete="off"/>

I know it is something with

onkeydown="if (event.keyCode == 27)
   <input type="text" id="search" size="25" autocomplete="off"/>

I know it is something with

onkeydown="if (event.keyCode == 27)
Share Improve this question asked Sep 1, 2010 at 7:07 jprimjprim 1,3532 gold badges16 silver badges22 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 11

Declare a function which will be called when a key is pressed:

function onkeypressed(evt, input) {
    var code = evt.charCode || evt.keyCode;
    if (code == 27) {
        input.value = '';
    }
}

And the corresponding markup:

<input type="text" id="search" size="25" autocomplete="off" 
       onkeydown="onkeypressed(event, this);" />
<input type="text" value="" onkeyup="if ( event.keyCode == 27 ) this.value=''" />

This should work.

$('input[type=text]').each(function (e) {
    $(this).keyup(function (evt) {
        var code = evt.charCode || evt.keyCode;
        if (code == 27) {
            $(this).val('');
        }
    })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" autofocus value="input data" placeholder="ESC button clear" style="padding:5px;">
<p>Hit esc button to see result</p>

function keyPressed(evt) {
 if (evt.keyCode == 27) {
    //clear your textbox content here...
    document.getElementById("search").value = '';
 }
}

Then in your input tag...

<input type="text" onkeypress="keyPressed(event)" id="search" ...>
发布评论

评论列表(0)

  1. 暂无评论