Javascript поле ввода числа

How to make HTML input tag only accept numerical values?

I need to make sure that a certain field only takes numbers as value. The input is not part of a form. Hence it doesn’t get submitted, so validating during submission is not an option. I want the user to be unable to type in any characters other than numbers. Is there a neat way to achieve this?

34 Answers 34

HTML 5

You can use HTML5 input type number to restrict only number entries:

This will work only in HTML5 complaint browser. Make sure your html document’s doctype is:

See also https://github.com/jonstipe/number-polyfill for transparent support in older browsers.

JavaScript

Update: There is a new and very simple solution for this:

It allows you to use any kind of input filter on a text , including various numeric filters. This will correctly handle Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, and all keyboard layouts.

For general purposes, you can have JS validation as below:

function isNumberKey(evt) < var charCode = (evt.which) ? evt.which : evt.keyCode if (charCode >31 && (charCode < 48 || charCode >57)) return false; return true; >

If you want to allow decimals replace the if-conditio» with this:

if (charCode > 31 && (charCode != 46 &&(charCode < 48 || charCode >57))) 

Yep, this works for me in both firefox and chrome. Weird that js is necessary for such a simple thing.

Doesn’t work in chrome 30. I have no trouble at all typing letters into your «number» input in the fiddle. Hmmm.

You can also use the pattern attribute in html5:

Although, if your doctype isn’t html then I think you’ll need to use some javascript/jquery.

Although firefox gives the input box a red border when non-numbers are typed, in both firefox and chrome, you are able to type non-number characters in the input box.

ok, maybe it’s not supported in the browser versions you have? Not 100% sure but to be honest I’d use some js to validate aswell, I wouldn’t rely purely on html5 at the moment

This will permit usage of numbers and backspace only.

If you need decimal part too, use this code fragment

it returns a boolean value so I guess you can add another check that takes the current value and checks if the length is under what you specified.

Please try this code along with the input field itself

You can use following one line code as :

It will accept numbers ony.

You can use an . This will only allow numbers to be entered into othe input box.

Please note that the input type=»number» tag is only supported in newer browsers.

For firefox, you can validate the input by using javascript:

Update 2018-03-12: Browser support is much better now it’s supported by the following:

  • Chrome 6+
  • Firefox 29+
  • Opera 10.1+
  • Safari 5+
  • Edge
  • (Internet Explorer 10+)

Ah. That is because firefox does not support input type=number. Alternatively, you could use some javascript to validate the input as the user inputs the text. Answer updated.

The jscript on jsfiddle.net/VmtF5, will also not work. Even if 1 digit is at the start of character, the validation fails. Try it yourself on jsfiddle

You can use the tag with attribute type=’number’

This input field allows only numerical values. You can also specify the minimum value and maximum value that should be accepted by this field.

I have used a regular expression to replace the input value with the pattern needed.

function restrictNumber(e) < var newValue = this.value.replace(new RegExp(/[^\d]/, 'ig'), ""); this.value = newValue; >var userName = document.querySelector('#numberField'); userName.addEventListener('input', restrictNumber);

or you can write it in a complicated but useful way:

Note: cross-browser and regex in literal.

Then you have to consider first and second characters ( 0.43 or .43 ) that could be done with checking the value of current input plus pressed key. This would be ugly in one-line code, I recommend to use a function for this. To test integer or float, check here.

function AllowOnlyNumbers(e) < e = (e) ? e : window.event; var clipboardData = e.clipboardData ? e.clipboardData : window.clipboardData; var key = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode; var str = (e.type && e.type == "paste") ? clipboardData.getData('Text') : String.fromCharCode(key); return (/^\d+$/.test(str)); >
inputField.addEventListener('input', function () < if ((inputField.value/inputField.value) !== 1) < console.log("Please enter a number"); >>);

onkeyup triggers when the key is released.

isNaN(parseFloat(value))? checks if the input value is not a number.

If it is not a number the value is set to 1000 : If it is a number the value is set to the value.

Note: For some reason it only works with type=»number»

To make it even more exciting, you can also have a boundary:

9000?1000:value" type="number" value="1000" > 

I fought with this one for a bit. Many solutions here and elsewhere seemed complicated. This solution uses jQuery/javascript alongside HTML.

$(document).on('change', '.validateNumber', function() < var abc = parseInt($(this).val()); if (isNaN(abc)) abc = 1; $(this).val(abc); >);

In my case I was tracking small quantities with a minimum value of 1, hence the min=»1″ in the input tag and abc = 1 in the isNaN() check. For positive-only numbers you could change those values to 0 and even simply remove the min=»1″ from the input tag to allow for negative numbers.

Also this works for multiple boxes (and could save you some load time over doing them individually by id), just add the «validateNumber» class where needed.

parseInt() basically does what you need, except that it returns NaN rather than some integer value. With a simple if() , you can set the «fallback» value that you prefer in all the cases NaN is returned.

Also, W3 Schools states here that the global version of NaN will type cast before checking which gives some extra proofing ( Number.isNaN() does not do that). Any values sent to a server/backend should still be validated there!

Источник

Ввод только цифр в поле input на JavaScript + вариант на HTML

Ввод только цифр в поле input на JavaScript + вариант на HTML

Сегодняшней темой нашего обсуждения является способ, благодаря которому в input мы сможем вводить только цифры. Также мы обсудим почему это важно.

Допустим, у нас интернет-магазин, и нашему клиенту нужно ввести свой индекс. В индексе нужно вводить только цифры. Пишем input type=number.

Давай попробуем сделать через JavaScript. К примеру через onchange, но при таком методе данные обновляются не сразу. Этот способ нам не подходит.

Нам же нужно сделать так, что бы это было в режиме реального времени(Real Time). Для этого нам нужен oninput. Пишем эту же функцию только в новом атрибуте, все работает!

Теперь можно всё убрать с помощью регулярных выражений и оставить только цифры. Для этого мы пишем «const value», и заносим «e.value». Затем мы приравниваем «e.value» к «value.replace«, т.е делаем замену. Далее идёт выражение «(/\D/g, ‘ ‘).

Вуаля! Теперь у нас только цифры. Нет никаких лишних символов, и всё стабильно!

Чтобы более подробно разобраться в данной теме «Ввод только цифр в поле input на JavaScript + вариант на HTML» советую посмотреть наше видео на эту тему:

Хочешь научиться создавать сайты? Изучи все на практике, с помощью интерактивных курсов у нас на проекте. Регистрация — Войти — Наши курсы. Задавайте вопросы в комментариях!

Источник

Javascript поле ввода числа

Часто возникает задача запрета ввода не цифровых значений в поле . В этом материале разберем реализацию данного механизма на JavaScript.

На мой взгляд, самый простой способ воспользоваться обработчиком события .keydown() — в jQuery или прослушивать событие keydown. Итак, предположим у нас есть текстовое поле с >

Алгоритм проверки будет такой

  1. При нажатии клавиши на клавиатуре ( событие .keydown() ) будем получать keyCode (возвращает код нажатой клавиши) и анализировать его;
  2. Для цифр основной клавиатуры keyCode принимает значения от 48 (клавиша 0) до 57 (клавиша 9);
  3. Для цифр дополнительной клавиатуры ( Num-клавиатуры ) keyCode принимает значения от 96 (клавиша 0) до 105 (клавиша 9);
  4. Так же разрешим:
    • удалять символы ( клавиша Del ) keyCode == 46;
    • переключаться клавишей Tab между полями keyCode == 9;
    • нажимать Backspace keyCode == 8;
    • нажимать Esc keyCode == 27;
    • выделять текст сочетанием Ctrl + A — вот тут клавиша A имеет код keyCode == 65, а событие зажатого Ctrl ctrlKey должно быть строго истина, т.е. получаем условие — ( event.keyCode == 65 && event.ctrlKey === true );
    • разрешим клавишу Home keyCode == 36;
    • разрешим клавишу End keyCode == 35;
    • разрешим клавишу влево keyCode == 37;
    • разрешим клавишу вправо keyCode == 39;

Разрешаем ввод только цифр в поле input на JavaScript

 const input = document.getElementById('only_num'); input.addEventListener('keydown', function(event) < // Разрешаем: backspace, delete, tab и escape if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || // Разрешаем: Ctrl+A (event.keyCode == 65 && event.ctrlKey === true) || // Разрешаем: home, end, влево, вправо (event.keyCode >= 35 && event.keyCode else < // Запрещаем все, кроме цифр на основной клавиатуре, а так же Num-клавиатуре if ((event.keyCode < 48 || event.keyCode >57) && (event.keyCode < 96 || event.keyCode >105 )) < event.preventDefault(); >> >); 

Разрешаем ввод только цифр в поле input на jQuery

 $(document).ready(function() < $("#only_num").keydown(function(event) < // Разрешаем: backspace, delete, tab и escape if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || // Разрешаем: Ctrl+A (event.keyCode == 65 && event.ctrlKey === true) || // Разрешаем: home, end, влево, вправо (event.keyCode >= 35 && event.keyCode else < // Запрещаем все, кроме цифр на основной клавиатуре, а так же Num-клавиатуре if ((event.keyCode < 48 || event.keyCode >57) && (event.keyCode < 96 || event.keyCode >105 )) < event.preventDefault(); >> >); >); 

Источник

Читайте также:  Меняем размер шрифта при помощи CSS
Оцените статью