Sie können mit JavaScript (zum Beispiel mit jQuery) nur bestimmte Zeichen ermöglichen:
// Catch all events related to changes
$('#textbox').on('change keyup', function() {
// Remove invalid characters
var sanitized = $(this).val().replace(/[^0-9]/g, '');
// Update value
$(this).val(sanitized);
});
Here eine Geige ist.
Die gleiche Sache mit Unterstützung für Schwimmer:
// Catch all events related to changes
$('#textbox').on('change keyup', function() {
// Remove invalid characters
var sanitized = $(this).val().replace(/[^0-9.]/g, '');
// Remove the first point if there is more than one
sanitized = sanitized.replace(/\.(?=.*\.)/, '');
// Update value
$(this).val(sanitized);
});
Und here ist eine andere Geige.
Aktualisierung: Obwohl Sie dies möglicherweise nicht benötigen, hier ist eine Lösung, die ein führendes Minuszeichen erlaubt.
// Catch all events related to changes
$('#textbox').on('change keyup', function() {
// Remove invalid characters
var sanitized = $(this).val().replace(/[^-0-9]/g, '');
// Remove non-leading minus signs
sanitized = sanitized.replace(/(.)-+/g, '$1');
// Update value
$(this).val(sanitized);
});
3rd fiddle
Und nun eine endgültige Lösung, die nur gültig Dezimalstellen (einschließlich Schwimmer und negative Zahlen) erlaubt:
// Catch all events related to changes
$('#textbox').on('change keyup', function() {
// Remove invalid characters
var sanitized = $(this).val().replace(/[^-.0-9]/g, '');
// Remove non-leading minus signs
sanitized = sanitized.replace(/(.)-+/g, '$1');
// Remove the first point if there is more than one
sanitized = sanitized.replace(/\.(?=.*\.)/g, '');
// Update value
$(this).val(sanitized);
});
Final fiddle
javascript Eingang zu fangen und alles zu löschen, was das ist, keine Nummer. –
@MarcB Wie mache ich das? – coder
Versuchen Sie dies, http://stackoverflow.com/questions/7295843/allow-only-numbers-to-be-typed-in-a-textbox –