Rileva backspace e canc sull'evento "input"?


93

Come farlo?

Provai:

var key = event.which || event.keyCode || event.charCode;

if(key == 8) alert('backspace');

ma non funziona ...

Se faccio lo stesso sull'evento keypress funziona, ma non voglio usare keypress perché restituisce il carattere digitato nel mio campo di input. Devo essere in grado di controllarlo


il mio codice:

  $('#content').bind('input', function(event){

    var text = $(this).val(),
        key = event.which || event.keyCode || event.charCode;

    if(key == 8){
      // here I want to ignore backspace and del
    }

    // here I'm doing my stuff
    var new_text = 'bla bla'+text;
    $(this).val(new_text);
  });

nessun carattere dovrebbe essere aggiunto al mio input, oltre a quello che sto aggiungendo con val () in realtà l'input dell'utente dovrebbe essere completamente ignorato, solo l'azione premendo il tasto è importante per me


3
In realtà non è necessario eseguire l'evento or'ing. Che va bene, jQuery normalizza l'oggetto evento per te. Vedi api.jquery.com/category/events/event-object
Niko

Dovresti inserire il nome dell'evento come primo argomento di .bind, non un selettore. Dovrebbe essere$('content').bind('keypress', ...
pmrotule

Risposte:


119

Utilizzare .onkeydowne annullare la rimozione con return false;. Come questo:

var input = document.getElementById('myInput');

input.onkeydown = function() {
    var key = event.keyCode || event.charCode;

    if( key == 8 || key == 46 )
        return false;
};

O con jQuery, perché hai aggiunto un tag jQuery alla tua domanda:

jQuery(function($) {
  var input = $('#myInput');
  input.on('keydown', function() {
    var key = event.keyCode || event.charCode;

    if( key == 8 || key == 46 )
        return false;
  });
});


19
E se volessi catturare l'input da un clic destro> incolla?
ctb

6
keydownnon funziona in Chrome Android, restituisce vuoto quando si fa clic su Backspace o Canc
Kosmetika

2
Nella funzione dobbiamo mantenere l'evento come parametro, solo che funzionerà come funzione (evento) -------------------------- var input = document. getElementById ('myInput'); input.onkeydown = funzione (evento) {var key = event.keyCode || event.charCode; if (key == 8 || key == 46) restituisce false; };
Anurag_BEHS

1
con jQuery filtra internamente entere backspacetasti inputeventi e queste pressioni dei tasti non arrivare
vsync

@ Wouter - Non che sia un grosso problema, ma penso che ci sia un errore di battitura nel codice per jquery. Penso che volessi aggiungere il nome del parametro "evento" al gestore di eventi on-keydown.
RoboBear

14

Con jQuery

La proprietà event.which normalizza event.keyCode e event.charCode. Si consiglia di guardare event.which per l'inserimento dei tasti della tastiera.

http://api.jquery.com/event.which/

jQuery('#input').on('keydown', function(e) {
    if( e.which == 8 || e.which == 46 ) return false;
});

2
Uso jQuery da molto tempo, ma non l'ho visto. Sempre buono per imparare qualcosa di nuovo. +1!
Sablefoste

9

event.key === "Backspace"

Più recente e molto più pulito: usa event.key. Niente più codici numerici arbitrari!

input.addEventListener('keydown', function(event) {
    const key = event.key; // const {key} = event; ES6+
    if (key === "Backspace" || key === "Delete") {
        return false;
    }
});

Mozilla Docs

Browser supportati


A volte event.key restituisce "Process" per un motivo che non riesco a capire ...
Oscar Chambers,

Questo è un browser supportato. Potresti avere un bug, o forse la tua tastiera personalizzata non
attiva gli

3

Hai provato a usare "onkeydown"? Questo è l'evento che stai cercando.

Funziona prima dell'inserimento dell'input e consente di annullare l'inserimento di caratteri.


ma come si annulla? perché sto usando val () sull'input e aggiunge ancora il carattere digitato
Alex

3
Che ne dici event.preventDefault()?
Niko

Puoi semplicemente return false;annullare qualsiasi evento quando usi jQuery.
iMoses

3

È una vecchia domanda, ma se si desidera rilevare un evento di backspace in input, e non keydown, keypress o keyup, poiché ho notato che ognuna di queste interrompe alcune funzioni che ho scritto e causa ritardi imbarazzanti con la formattazione automatica del testo —Puoi catturare un backspace usando inputType:

document.getElementsByTagName('input')[0].addEventListener('input', function(e) {
    if (e.inputType == "deleteContentBackward") {
        // your code here
    }
});

3

keydown con event.key === "Backspace" or "Delete"

Più recente e molto più pulito: usa event.key. Niente più codici numerici arbitrari!

input.addEventListener('keydown', function(event) {
    const key = event.key; // const {key} = event; ES6+
    if (key === "Backspace" || key === "Delete") {
        return false;
    }
});

Stile moderno:

input.addEventListener('keydown', ({key}) => {
    if (["Backspace", "Delete"].includes(key)) {
        return false
    }
})

Mozilla Docs

Browser supportati


2
$('div[contenteditable]').keydown(function(e) {
// trap the return key being pressed
if (e.keyCode === 13 || e.keyCode === 8)
{
    return false;
}
});

1
Codice chiave 8 per "BackSpace"
Phanikumar Jatavallabhula

La domanda riguarda backspace ed elimina, non backspace e invio.
Paul

0
//Here's one example, not sure what your application is but here is a relevant and likely application 
function addDashesOnKeyUp()
{
    var tb = document.getElementById("tb1"); 
    var key = event.which || event.keyCode || event.charCode;

    if((tb.value.length ==3 || tb.value.length ==7 )&& (key !=8) ) 
    {
        tb.value += "-"
    } 
}

0

sui dispositivi Android che utilizzano Chrome non siamo in grado di rilevare un backspace. Puoi usare una soluzione alternativa per questo:

var oldInput = '',
    newInput = '';

 $("#ID").keyup(function () {
  newInput = $('#ID').val();
   if(newInput.length < oldInput.length){
      //backspace pressed
   }
   oldInput = newInput;
 })

Non voglio davvero che questa sia la risposta, ma sembra che lo sia, dal momento che sono impostati whiche keyCodesu 229. Ci deve essere un modo migliore, o un modo migliore in arrivo, ma per ora lo userò fondamentalmente. ..
JohnnyFun
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.