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?
Nota: Questa è una risposta aggiornata. I commenti qui sotto si riferiscono ad una vecchia versione che pasticciava con i keycode;
**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):
// 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 <= 500
(value === "" || parseInt(value) <= 500);
return /^-?\d*[.,]?\d*$/.test(value); // Float (accept both '.' and ',' as decimal separator)
return /^-?\d*[.,]?\d{0,2}$/.test(value); // Currency (i.e. at most two decimal places)
return /^[a-z]*$/i.test(value); // A-Z only
return /^[0-9a-f]*$/i.test(value); // Hexadecimal
**Nota che devi ancora fare la validazione lato server!
jQuery non è effettivamente necessario per questo, si può fare la stessa cosa anche con puro JavaScript. Vedi questa risposta o prova tu stesso [su JSFiddle][4].
HTML 5 ha una soluzione nativa con <input type="number">
(vedi la specifica), ma si noti che il supporto del browser varia:
step
, min
e max
.e
e E
nel campo. Vedi anche questa domanda.Prova tu stesso su w3schools.com.
$(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
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()"/>