Html input type number onchange

Событие onchange для типа ввода = «число»

Как я могу обрабатывать onchange для ? Я не могу сделать keyup или keydown , потому что пользователь может просто использовать стрелки для изменения значения. Я хотел бы обрабатывать его всякий раз, когда он изменяется, а не только на размытие, которое, по-моему, имеет событие .change() . Любые идеи?

10 ответов

Используйте мышь и клавиатуру

$(":input").bind('keyup mouseup', function () < alert("changed"); >); 

Да, это будет. Если это проблема, вы должны отслеживать значение на входе в глобальной переменной или в элементе данных на входе. Когда событие mouseup вызывает вашу функцию, сравните это значение с текущим значением ввода. Делайте что-то, только если значение изменилось.

Читайте также:  Генератор штрих кодов питон

Если пользователь удерживает нажатой клавишу со стрелкой, чтобы изменить значение, он не срабатывает, пока не будет отпущена клавиша со стрелкой. Использование input вместо (как предложено в другом ответе), кажется, работает лучше.

Событие oninput ( .bind(‘input’, fn) ) охватывает любые изменения от нажатий клавиш до щелчков стрелок и вставки клавиатуры/мыши, но не поддерживается в IE

$(":input").bind('keyup change click', function (e) < if (! $(this).data("previousValue") || $(this).data("previousValue") != $(this).val() ) < console.log("changed"); $(this).data("previousValue", $(this).val()); >>); $(":input").each(function () < $(this).data("previousValue", $(this).val()); >);​ 

Это немного гетто, но таким образом вы можете использовать событие «click» для захвата события, которое выполняется, когда вы используете мышь для увеличения/уменьшения с помощью маленьких стрелок на входе. Вы можете увидеть, как я построил небольшую ручную процедуру проверки изменений, которая гарантирует, что ваша логика не будет срабатывать, если значение фактически не изменится (чтобы предотвратить ложные срабатывания от простых щелчков в поле).

Источник

What Events Does an Fire When Its Value Is Changed

What events does an input type=number / fire when its value is changed?

change would be the event that is fired when the field’s value changes.

I think the HTML5 event input would also fire.

onchange event for input type=number

$(":input").bind('keyup mouseup', function () alert("changed"); 
>);

What JQuery event fires when you change the value (and hold) of an input type number?

$('[type="number"]').on('input', function(e) < console.log(e.type)>)
Use keyboard arrows or Input's UI arrows:

Best way to track onchange as-you-type in input type=text?

So, you want the onchange event to fire on keydown, blur, and paste? That’s magic.

If you want to track changes as they type, use «onkeydown» . If you need to trap paste operations with the mouse, use «onpaste» (IE, FF3) and «oninput» (FF, Opera, Chrome, Safari 1 ).

1 Broken for on Safari. Use textInput instead

onchange event on input type=range is not triggering in Firefox while dragging

Apparently Chrome and Safari are wrong: onchange should only be triggered when the user releases the mouse. To get continuous updates, you should use the oninput event, which will capture live updates in Firefox, Safari and Chrome, both from the mouse and the keyboard.

However, oninput is not supported in IE10, so your best bet is to combine the two event handlers, like this:

 min="5" 
max="10"
step="1"
oninput="showVal(this.value)"
onchange="showVal(this.value)"
/>

Check out this Bugzilla thread for more information.

html input type=text / onchange event not working

onchange is only triggered when the control is blurred. Try onkeypress instead.

Event when input value is changed by JavaScript?

Based on @t-j-crowder and @maciej-swist answers, let’s add this one, with «.apply» function that prevent infinite loop without redefining the object.

 function customInputSetter() 
var descriptor = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value");
var originalSet = descriptor.set;

// define our own setter
descriptor.set = function(val) console.log("Value set", this, val);
originalSet.apply(this,arguments);
>

Object.defineProperty(HTMLInputElement.prototype, "value", descriptor);
>

jQuery — Detect value change on hidden input field

So this is way late, but I’ve discovered an answer, in case it becomes useful to anyone who comes across this thread.

Changes in value to hidden elements don’t automatically fire the .change() event. So, wherever it is that you’re setting that value, you also have to tell jQuery to trigger it.

function setUserID(myValue) $('#userid').val(myValue) 
.trigger('change');
>
$('#userid').change(function() //fire your ajax call 
>)

How to detect input type=file change for the same file?

You can trick it. Remove the file element and add it in the same place on change event. It will erase the file path making it changeable every time.

Example on jsFiddle.

Or you can simply use .prop(«value», «») , see this example on jsFiddle.

Источник

Input type number

В HTML5 появилось специальное поле с атрибутом type=»number» для вода чисел. Рассмотрим его возможности.

Для поля доступны следующие атрибуты:

Атрибут Описание
step Шаг изменения значения
max Максимальное значение
min Минимальное значение
placeholder Подсказка
readonly Только для чтения
disabled Заблокирован
list Связка со списком опций datalist по id
required Обязательный для заполнения

Шаг изменения

Атрибут step=»1″ задает на сколько будет увеличиваться или уменьшаться значение в поле. Может быть как целым (10) так и дробным (0.1).

Пример:

Минимальное значение

Атрибут min=»1″ задает минимально возможное значение value . Это значение должно быть меньше или равно значению max . Может быть целым, отрицательным или дробным.

Пример:

Максимальное значение

Атрибут max=»100″ задает максимально возможное значение value .

Пример:

Опции по умолчанию

У поля есть возможность задать список с рекомендуемыми значениями с помощью элемента .

Пример:

Валидация

Если указать атрибут required , то при отправки формы будет проверятся заполнено поле или нет, а также превышение введенного значения value в атрибутах min и max .

Проверить значение регулярным выражением с помощью атрибута pattern не получится, т.к. он не поддерживается.

Пример:

Также доступны CSS псевдо свойства :invalid и :valid , с помощью них можно применить стили к неправильно заполненному полю.

input[type="number"]:invalid+span:after < content: '✖'; padding-left: 5px; color: red; >input[type="number"]:valid+span:after

Источник

Html input type number onchange

Last updated: Jan 15, 2023
Reading time · 4 min

banner

# Table of Contents

# Create a Numbers only Input field in React.js

To create an input field with only numbers allowed in React.js:

  1. Set the type of the input field to text .
  2. Add an onChange event handler that removes all non-numeric values.
  3. Keep the input value in a state variable.
Copied!
import useState> from 'react'; const App = () => const [value, setValue] = useState(''); const handleChange = event => const result = event.target.value.replace(/\D/g, ''); setValue(result); >; console.log(value); console.log(typeof value); console.log(Number(value)); return ( div> div>!Hello 123 World 456?___div> input type="text" placeholder="Your fav number" value=value> onChange=handleChange> /> div> ); >; export default App;

We used the useState hook to keep track of the input field’s value.

Every time the input’s value is changed, the handleChange function is triggered.

We passed the following 2 arguments to the String.replace method to remove all non-digit characters.

Name Description
regexp a regular expression we want to match in the string
replacement the replacement for each match

The \D character matches a character that is NOT a digit.

We added the g (global) flag to match all non-digit characters and replace them with an empty string.

This means that if the string only contains non-digit characters we would replace all of them with empty strings and the String.replace method would return an empty string.

If you need to restrict an input field to only letters, check out the following article.

# Handling an empty input value

You might have to handle the scenario where the user doesn’t enter any numbers into the input field.

Then the state variable would be an empty string and you might not want to convert an empty string to a number because you’d get 0 .

Copied!
import useState> from 'react'; const App = () => const [value, setValue] = useState(''); const handleChange = event => const result = event.target.value.replace(/\D/g, ''); setValue(result); >; console.log(value); console.log(typeof value); console.log(Number(value)); // 👇️ validation if (value !== '') const num = Number(value); // 👉️ submit form > return ( div> div>!Hello 123 World 456?___div> input type="text" placeholder="Your fav number" value=value> onChange=handleChange> /> div> ); >; export default App;

You can make sure that the input doesn’t store an empty string value and then convert the value to a number.

# Using an input field of type number

Alternatively, you can use an input type number , but that would allow the user to enter characters like e , — , . , etc.

Copied!
import useState> from 'react'; const App = () => const [value, setValue] = useState(''); const handleChange = event => setValue(event.target.value); >; console.log(value); console.log(typeof value); console.log(Number(value)); return ( div> div>.Hello- 123 World 456?___div> input type="number" placeholder="Your fav number" value=value> onChange=handleChange> /> div> ); >; export default App;

Note that even though the input has its type set to number , its value is still of type string .

Источник

Оцените статью