Html input tag events

HTMLElement: input event

The input event fires when the value of an , , or element has been changed.

The event also applies to elements with contenteditable enabled, and to any element when designMode is turned on. In the case of contenteditable and designMode , the event target is the editing host. If these properties apply to multiple elements, the editing host is the nearest ancestor element whose parent isn’t editable.

For elements with type=checkbox or type=radio , the input event should fire whenever a user toggles the control, per the HTML Living Standard specification. However, historically this has not always been the case. Check compatibility, or use the change event instead for elements of these types.

Note: The input event is fired every time the value of the element changes. This is unlike the change event, which only fires when the value is committed, such as by pressing the enter key, selecting a value from a list of options, and the like.

Syntax

Use the event name in methods like addEventListener() , or set an event handler property.

addEventListener("input", (event) => >); oninput = (event) => >; 

Event type

Examples

This example logs the value whenever you change the value of the element.

HTML

input placeholder="Enter some text" name="name" /> p id="values">p> 

JavaScript

const input = document.querySelector("input"); const log = document.getElementById("values"); input.addEventListener("input", updateValue); function updateValue(e)  log.textContent = e.target.value; > 

Result

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Apr 7, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

События: change, input, cut, copy, paste

Давайте рассмотрим различные события, сопутствующие обновлению данных.

Событие: change

Событие change срабатывает по окончании изменения элемента.

Для текстовых это означает, что событие происходит при потере фокуса.

Пока мы печатаем в текстовом поле в примере ниже, событие не происходит. Но когда мы перемещаем фокус в другое место, например, нажимая на кнопку, то произойдёт событие change :

Для других элементов: select , input type=checkbox/radio событие запускается сразу после изменения значения:

 

Событие: input

Событие input срабатывает каждый раз при изменении значения.

В отличие от событий клавиатуры, оно работает при любых изменениях значений, даже если они не связаны с клавиатурными действиями: вставка с помощью мыши или распознавание речи при диктовке текста.

Если мы хотим обрабатывать каждое изменение в , то это событие является лучшим выбором.

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

Событие input происходит после изменения значения.

Поэтому мы не можем использовать event.preventDefault() там – будет уже слишком поздно, никакого эффекта не будет.

События: cut, copy, paste

Эти события происходят при вырезании/копировании/вставке данных.

Они относятся к классу ClipboardEvent и обеспечивают доступ к копируемым/вставляемым данным.

Мы также можем использовать event.preventDefault() для предотвращения действия по умолчанию, и в итоге ничего не скопируется/не вставится.

Например, код, приведённый ниже, предотвращает все подобные события и показывает, что мы пытаемся вырезать/копировать/вставить:

Технически, мы можем скопировать/вставить всё. Например, мы можем скопировать файл из файловой системы и вставить его.

Существует список методов в спецификации для работы с различными типами данных, чтения/записи в буфер обмена.

Но обратите внимание, что буфер обмена работает глобально, на уровне ОС. Большинство браузеров в целях безопасности разрешают доступ на чтение/запись в буфер обмена только в рамках определённых действий пользователя, к примеру, в обработчиках событий onclick .

Также запрещается генерировать «пользовательские» события буфера обмена при помощи dispatchEvent во всех браузерах, кроме Firefox.

Итого

Событие Описание Особенности
change Значение было изменено. Для текстовых полей срабатывает при потере фокуса.
input Срабатывает при каждом изменении значения. Запускается немедленно, в отличие от change .
cut/copy/paste Действия по вырезанию/копированию/вставке. Действие можно предотвратить. Свойство event.clipboardData предоставляет доступ на чтение/запись в буфер обмена…

Задачи

Депозитный калькулятор

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

Любое изменение введённых данных должно быть обработано немедленно.

// initial: начальная сумма денег // interest: проценты, например, 0.05 означает 5% в год // years: сколько лет ждать let result = Math.round(initial * (1 + interest) ** years);

Источник

HTML DOM InputEvent

The InputEvent Object handles events that occur when an input element is changed.

Input Events

InputEvent Properties

Property Returns
data The inserted characters
dataTransfer An object containing information about the inserted/deleted data
inputType The type of the change (i.e «inserting» or «deleting»)
isComposing If the state of the event is composing or not

InputEvent Methods

Method Returns
getTargetRanges() An array containing target ranges that will be affected by the insertion/deletion

Inherited Properties and Methods

The InputEvent inherits all the properties and methods from:

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Читайте также:  Css нет прицела крестика
Оцените статью