tags:

views:

32

answers:

2

i have a input tag which is non editable, but some times i need to remove the text inside that by pressing delete or back space keys. how can i do that?

+1  A: 

I would advise against using the backspace key, since that is usually associated with the browser's back button.

Here is how to solve your problem with .keyup() and only the delete key (jQuery normalizes e.which):

$(document).keyup(function(e) {
    if (e.which == 46) {                     // 46 is the code for the delete key
        $(inputSelector).val("");
    }
});

jsFiddle example


Quirksmode has a useful page on detecting keystrokes..

The above captures key presses anywhere on the page by attaching the .keyup() to the document. You must do this, since the input is not editable.

You could also use keydown(), but it's best not to use keypress().

keydown and keyup provide a code indicating which key is pressed, while keypress indicates which character was entered. Because of this distinction, when catching special keystrokes such as arrow keys, .keydown() or .keyup() is a better choice.

Peter Ajtai
A: 

As an erasable non-editable input element seems like a strange concept, you'd better add a 'reset/erase' control next to your text input, a control that would have the same function and behavior (including keybind).

<p>
  <input type="text" readonly="readonly" value="I can't be edited">
  <input type="submit" value="(reset)" title="Suppress text in the previous input">
</p>

Value and title are only examples, the latter should describe what is the purpose of the submit control in a non-ambiguous way (there can be many reset controls and obviously a true submission form element).

Beware that many keys are already used by browsers, browser plugins, other programs that enhance the keyboard like AutoHotkey and macros) and that blind people use screen readers that use nearly all combination of keys and dead keys you can think of in their browser; thus please provide a mechanism that can disable your feature.

Felipe Alsacreations