Jak zezwolić tylko numeryczne (0-9) w HTML inputbox przy użyciu jQuery?
Tworzę stronę internetową, na której mam pole tekstowe, w którym chcę zezwolić tylko na znaki numeryczne, takie jak (0,1,2,3,4,5...9) 0-9.
Jak mogę to zrobić używając jQuery?
30 answers
Spójrz na tę wtyczkę (widelec numerycznej wtyczki jQuery texotela) . Ten (jStepper) jest inny.
This is a link if you want to build it yourself.
$(document).ready(function() {
$("#txtboxToFilter").keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
// Allow: Ctrl+A, Command+A
(e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
// Allow: home, end, left, right, down, up
(e.keyCode >= 35 && e.keyCode <= 40)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
});
Uwaga: jeśli Twoja strona używa HTML5, możesz użyć wbudowanych <input type="number">
i użyć właściwości min
i max
do kontrolowania minimalnej i maksymalnej wartości.
Poniższy tekst jest zminimalizowany i pozwala na użycie CTRL+X , CTRL+C i CTRL+V
$(function() {
$('#staticParent').on('keydown', '#child', function(e){-1!==$.inArray(e.keyCode,[46,8,9,27,13,110])||(/65|67|86|88/.test(e.keyCode)&&(e.ctrlKey===true||e.metaKey===true))&&(!0===e.ctrlKey||!0===e.metaKey)||35<=e.keyCode&&40>=e.keyCode||(e.shiftKey||48>e.keyCode||57<e.keyCode)&&(96>e.keyCode||105<e.keyCode)&&e.preventDefault()});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="staticParent">
<input id="child" type="textarea" />
</div>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-28 06:59:05
Oto funkcja, której używam:
// Numeric only control handler
jQuery.fn.ForceNumericOnly =
function()
{
return this.each(function()
{
$(this).keydown(function(e)
{
var key = e.charCode || e.keyCode || 0;
// allow backspace, tab, delete, enter, arrows, numbers and keypad numbers ONLY
// home, end, period, and numpad decimal
return (
key == 8 ||
key == 9 ||
key == 13 ||
key == 46 ||
key == 110 ||
key == 190 ||
(key >= 35 && key <= 40) ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
});
});
};
Możesz następnie dołączyć go do swojego kontrolera, wykonując:
$("#yourTextBoxName").ForceNumericOnly();
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-27 23:13:27
Inline:
<input name="number" onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')">
Styl dyskretny (z jQuery):
$('input[name="number"]').keyup(function(e)
{
if (/\D/g.test(this.value))
{
// Filter non-digits from input value.
this.value = this.value.replace(/\D/g, '');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="number">
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-05 07:18:12
Możesz użyć prostego wyrażenia regularnego JavaScript do testowania znaków czysto numerycznych:
/^[0-9]+$/.test(input);
Zwraca true, jeśli Dane wejściowe są liczbowe lub false, jeśli nie.
Lub dla kodu klucza zdarzenia, proste użycie poniżej:
// Allow: backspace, delete, tab, escape, enter, ctrl+A and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
var charValue = String.fromCharCode(e.keyCode)
, valid = /^[0-9]+$/.test(charValue);
if (!valid) {
e.preventDefault();
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-11 13:04:43
Możesz użyć zdarzenia input w następujący sposób:
$(document).on("input", ".numeric", function() {
this.value = this.value.replace(/\D/g,'');
});
Ale co to za przywilej kodowania?
- działa na przeglądarkach mobilnych (keydown i keyCode mają problem).
- działa również na zawartości generowanej przez AJAX, ponieważ używamy "on".
- Lepsza wydajność niż keydown, na przykład przy zdarzeniu wklej.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-14 06:20:21
Użyj funkcji JavaScript isNaN ,
if (isNaN($('#inputid').val()))
if (isNaN (document.getElementById ("inputid").val()))
if (isNaN(document.getElementById('inputid').value))
Aktualizacja: A tutaj fajny artykuł mówiący o tym, ale używając jQuery: ograniczający wprowadzanie w tekstach HTML wartości liczbowych
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-22 09:58:24
Krótko i słodko - nawet jeśli to nigdy nie znajdzie wiele uwagi po 30 + odpowiedzi ;)
$('#number_only').bind('keyup paste', function(){
this.value = this.value.replace(/[^0-9]/g, '');
});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-10 05:52:41
$(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();
}
}
});
});
Źródło: http://snipt.net/GerryEng/jquery-making-textfield-only-accept-numeric-values
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-06-15 09:26:59
Używam tego w naszym wewnętrznym pliku JS. Dodaję tylko klasę do każdego wejścia, które potrzebuje takiego zachowania.
$(".numericOnly").keypress(function (e) {
if (String.fromCharCode(e.keyCode).match(/[^0-9]/g)) return false;
});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-02-14 19:47:32
Prostszym dla mnie jest
jQuery('.plan_eff').keyup(function () {
this.value = this.value.replace(/[^1-9\.]/g,'');
});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-05-08 14:09:01
Dlaczego tak skomplikowane? Nie potrzebujesz nawet jQuery, ponieważ istnieje atrybut wzorca HTML5:
<input type="text" pattern="[0-9]*">
Fajne jest to, że przywołuje klawiaturę numeryczną na urządzeniach mobilnych, co jest o wiele lepsze niż używanie jQuery.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-29 19:27:02
Możesz zrobić to samo, używając tego bardzo prostego rozwiązania
$("input.numbers").keypress(function(event) {
return /\d/.test(String.fromCharCode(event.keyCode));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="numbers" name="field_name" />
Odwołałem się do tego linku dla rozwiązania. Działa idealnie!!!
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-05 07:20:46
Atrybut pattern w HTML5 określa Wyrażenie regularne, z którym sprawdzana jest wartość elementu.
<input type="text" pattern="[0-9]{1,3}" value="" />
Uwaga: atrybut pattern działa z następującymi typami wprowadzania: tekst, Wyszukiwanie, adres url, tel, e-mail i hasło.
[0-9] można zastąpić dowolnym warunkiem wyrażenia regularnego.
{1,3} można wprowadzić minimum 1 cyfrę, a maksymalnie 3 cyfry.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-03 20:53:21
Możesz wypróbować numer HTML5 Wejście:
<input type="number" value="0" min="0">
Dla przeglądarek niezgodnych są Modernizr i Webforms2 fallbacks.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-12-22 22:36:54
Coś dość prostego używając jQuery.validate
$(document).ready(function() {
$("#formID").validate({
rules: {
field_name: {
numericOnly:true
}
}
});
});
$.validator.addMethod('numericOnly', function (value) {
return /^[0-9]+$/.test(value);
}, 'Please only enter numeric values (0-9)');
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-28 10:10:47
Function supressnonnumericinput (event) {
if( !(event.keyCode == 8 // backspace
|| event.keyCode == 46 // delete
|| (event.keyCode >= 35 && event.keyCode <= 40) // arrow keys/home/end
|| (event.keyCode >= 48 && event.keyCode <= 57) // numbers on keyboard
|| (event.keyCode >= 96 && event.keyCode <= 105)) // number on keypad
) {
event.preventDefault(); // Prevent character input
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-07-12 20:38:09
Doszedłem do bardzo dobrego i prostego rozwiązania, które nie uniemożliwia użytkownikowi wybierania tekstu lub kopiowania wklejania, jak to robią inne rozwiązania. jQuery style:)
$("input.inputPhone").keyup(function() {
var jThis=$(this);
var notNumber=new RegExp("[^0-9]","g");
var val=jThis.val();
//Math before replacing to prevent losing keyboard selection
if(val.match(notNumber))
{ jThis.val(val.replace(notNumber,"")); }
}).keyup(); //Trigger on page load to sanitize values set by server
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-19 21:07:51
Możesz użyć tej funkcji 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;
}
}
}
I możesz powiązać go ze swoją skrzynką tekstową w następujący sposób:
$(document).ready(function() {
$('#myTextbox').keydown(maskInput);
});
Używam powyższego w produkcji, i działa idealnie, i jest cross-browser. Co więcej, nie zależy od jQuery, więc możesz powiązać go z pole tekstowe za pomocą wbudowanego JavaScript:
<input type="text" name="aNumberField" onkeydown="javascript:maskInput()"/>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-11-19 23:59:42
Myślę, że to pomoże wszystkim
$('input.valid-number').bind('keypress', function(e) {
return ( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)) ? false : true ;
})
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-04-05 07:18:09
Oto szybkie rozwiązanie, które stworzyłem jakiś czas temu. więcej na ten temat możecie przeczytać w moim artykule:
Http://ajax911.com/numbers-numeric-field-jquery/
$("#textfield").bind("keyup paste", function(){
setTimeout(jQuery.proxy(function() {
this.val(this.val().replace(/[^0-9]/g, ''));
}, $(this)), 0);
});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-05-24 20:05:46
Oto odpowiedź, która używa jQuery UI Widget factory. Możesz łatwo dostosować, jakie znaki są dozwolone.
$('input').numberOnly({
valid: "0123456789+-.$,"
});
To pozwalałoby na liczby, znaki liczbowe i kwoty w dolarach.
$.widget('themex.numberOnly', {
options: {
valid : "0123456789",
allow : [46,8,9,27,13,35,39],
ctrl : [65],
alt : [],
extra : []
},
_create: function() {
var self = this;
self.element.keypress(function(event){
if(self._codeInArray(event,self.options.allow) || self._codeInArray(event,self.options.extra))
{
return;
}
if(event.ctrlKey && self._codeInArray(event,self.options.ctrl))
{
return;
}
if(event.altKey && self._codeInArray(event,self.options.alt))
{
return;
}
if(!event.shiftKey && !event.altKey && !event.ctrlKey)
{
if(self.options.valid.indexOf(String.fromCharCode(event.keyCode)) != -1)
{
return;
}
}
event.preventDefault();
});
},
_codeInArray : function(event,codes) {
for(code in codes)
{
if(event.keyCode == codes[code])
{
return true;
}
}
return false;
}
});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-03-25 20:15:24
To wydaje się nie do złamania.
// Prevent NULL input and replace text.
$(document).on('change', 'input[type="number"]', function (event) {
this.value = this.value.replace(/[^0-9\.]+/g, '');
if (this.value < 1) this.value = 0;
});
// Block non-numeric chars.
$(document).on('keypress', 'input[type="number"]', function (event) {
return (((event.which > 47) && (event.which < 58)) || (event.which == 13));
});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-06-26 12:52:46
Chciałem trochę pomóc i zrobiłem swoją wersję, funkcję onlyNumbers
...
function onlyNumbers(e){
var keynum;
var keychar;
if(window.event){ //IE
keynum = e.keyCode;
}
if(e.which){ //Netscape/Firefox/Opera
keynum = e.which;
}
if((keynum == 8 || keynum == 9 || keynum == 46 || (keynum >= 35 && keynum <= 40) ||
(event.keyCode >= 96 && event.keyCode <= 105)))return true;
if(keynum == 110 || keynum == 190){
var checkdot=document.getElementById('price').value;
var i=0;
for(i=0;i<checkdot.length;i++){
if(checkdot[i]=='.')return false;
}
if(checkdot.length==0)document.getElementById('price').value='0';
return true;
}
keychar = String.fromCharCode(keynum);
return !isNaN(keychar);
}
Wystarczy dodać input tag "...wejście ... id = "price" onkeydown= " return onlyNumbers (event)"..."i Gotowe;)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-07-29 02:32:30
Napisałem swoje na podstawie postu @ user261922 powyżej, lekko zmodyfikowany, więc możesz wybrać wszystkie, zakładkę i obsługiwać wiele pól "tylko Liczba" na tej samej stronie.
var prevKey = -1, prevControl = '';
$(document).ready(function () {
$(".OnlyNumbers").keydown(function (event) {
if (!(event.keyCode == 8 // backspace
|| event.keyCode == 9 // tab
|| event.keyCode == 17 // ctrl
|| event.keyCode == 46 // delete
|| (event.keyCode >= 35 && event.keyCode <= 40) // arrow keys/home/end
|| (event.keyCode >= 48 && event.keyCode <= 57) // numbers on keyboard
|| (event.keyCode >= 96 && event.keyCode <= 105) // number on keypad
|| (event.keyCode == 65 && prevKey == 17 && prevControl == event.currentTarget.id)) // ctrl + a, on same control
) {
event.preventDefault(); // Prevent character input
}
else {
prevKey = event.keyCode;
prevControl = event.currentTarget.id;
}
});
});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-08-09 20:35:21
Ja też chciałbym odpowiedzieć :)
$('.justNum').keydown(function(event){
var kc, num, rt = false;
kc = event.keyCode;
if(kc == 8 || ((kc > 47 && kc < 58) || (kc > 95 && kc < 106))) rt = true;
return rt;
})
.bind('blur', function(){
num = parseInt($(this).val());
num = isNaN(num) ? '' : num;
if(num && num < 0) num = num*-1;
$(this).val(num);
});
To wszystko...tylko liczby. :) Prawie może działać tylko z "rozmyciem", ale...Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-01-19 00:24:09
Chcesz zezwolić na zakładkę:
$("#txtboxToFilter").keydown(function(event) {
// Allow only backspace and delete
if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 ) {
// 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.keyCode < 96 || event.keyCode > 105 )) {
event.preventDefault();
}
}
});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-11-10 07:27:24
Prosty sposób na sprawdzenie, czy wprowadzana wartość jest liczbowa to:
var checknumber = $('#textbox_id').val();
if(jQuery.isNumeric(checknumber) == false){
alert('Please enter numeric value');
$('#special_price').focus();
return;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-22 06:59:05
Wystarczy zastosować tę metodę w Jquery i możesz zweryfikować swoje pole tekstowe, aby zaakceptować tylko numer.
function IsNumberKeyWithoutDecimal(element) {
var value = $(element).val();
var regExp = "^\\d+$";
return value.match(regExp);
}
Spróbuj tego rozwiązania tutaj
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-29 05:29:01
Możesz spróbować wprowadzić numer HTML5:
<input type="number" placeholder="enter the number" min="0" max="9">
Ten element znacznika wejściowego będzie teraz przyjmował wartość tylko z zakresu od 0 do 9 atrybut min jest ustawiony na 0, a atrybut max na 9.
Aby uzyskać więcej informacji na temat wizyty http://www.w3schools.com/html/html_form_input_types.asp
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-14 17:05:35
Musisz się upewnić, że klawiatura numeryczna i klawisz tab też działają
// Allow only backspace and delete
if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9) {
// 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.keyCode >= 96 && event.keyCode <= 105)) {
}
else {
event.preventDefault();
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-10-16 07:13:21