Come permettere solo numeri (0-9) in HTML inputbox usando jQuery?

Sto creando una pagina web dove ho un campo di testo in cui voglio permettere solo caratteri numerici come (0,1,2,3,4,5...9) 0-9.

Come posso fare questo usando jQuery?

Soluzione

Nota: Questa è una risposta aggiornata. I commenti qui sotto si riferiscono ad una vecchia versione che pasticciava con i keycode;

jQuery

**Prova tu stesso [su JSFiddle][1].

Non c'è un'implementazione nativa di jQuery per questo, ma è possibile filtrare i valori di input di un testo <input> con il seguente plugin inputFilter (supporta Copy+Paste, Drag+Drop, scorciatoie da tastiera, operazioni del menu contestuale, tasti non digitabili, la posizione del caret, diversi layout di tastiera e [tutti i browser da IE 9][2]):

// Restricts input for the set of matched elements to the given inputFilter function.
(function($) {
  $.fn.inputFilter = function(inputFilter) {
    return this.on("input keydown keyup mousedown mouseup select contextmenu drop", function() {
      if (inputFilter(this.value)) {
        this.oldValue = this.value;
        this.oldSelectionStart = this.selectionStart;
        this.oldSelectionEnd = this.selectionEnd;
      } else if (this.hasOwnProperty("oldValue")) {
        this.value = this.oldValue;
        this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
      }
    });
  };
}(jQuery));

È ora possibile usare il plugin inputFilter per installare un filtro di input:

$(document).ready(function() {
  $("#myTextBox").inputFilter(function(value) {
    return /^\d*$/.test(value);    // Allow digits only, using a RegExp
  });
});

Qui ci sono altri esempi di filtri di input che potrebbero essere utili:


return /^-?\d*$/.test(value);                // Integer
return /^\d*$/.test(value);                  // Integer >= 0
return /^\d*$/.test(value) &&                // Integer >= 0 and 
Commentari (30)
$(document).ready(function() {
    $("#txtboxToFilter").keydown(function(event) {
        // Allow only backspace and delete
        if ( event.keyCode == 46 || event.keyCode == 8 ) {
            // let it happen, don't do anything
        }
        else {
            // Ensure that it is a number and stop the keypress
            if (event.keyCode < 48 || event.keyCode > 57 ) {
                event.preventDefault(); 
            }   
        }
    });
});

Fonte: http://snipt.net/GerryEng/jquery-making-textfield-only-accept-numeric-values

Commentari (4)

Potete usare questa funzione JavaScript:

function maskInput(e) {
    //check if we have "e" or "window.event" and use them as "event"
        //Firefox doesn't have window.event 
    var event = e || window.event 

    var key_code = event.keyCode;
    var oElement = e ? e.target : window.event.srcElement;
    if (!event.shiftKey && !event.ctrlKey && !event.altKey) {
        if ((key_code > 47 && key_code < 58) ||
            (key_code > 95 && key_code < 106)) {

            if (key_code > 95)
                 key_code -= (95-47);
            oElement.value = oElement.value;
        } else if(key_code == 8) {
            oElement.value = oElement.value;
        } else if(key_code != 9) {
            event.returnValue = false;
        }
    }
}

E puoi legarla alla tua casella di testo in questo modo:

$(document).ready(function() {
    $('#myTextbox').keydown(maskInput);
});

Io uso quanto sopra in produzione, e funziona perfettamente, ed è cross-browser. Inoltre, non dipende da jQuery, quindi puoi legarlo alla tua casella di testo con JavaScript in linea:

<input type="text" name="aNumberField" onkeydown="javascript:maskInput()"/>
Commentari (1)