Javascript событие изменения input

Events: change, input, cut, copy, paste

Let’s cover various events that accompany data updates.

Event: change

The change event triggers when the element has finished changing.

For text inputs that means that the event occurs when it loses focus.

For instance, while we are typing in the text field below – there’s no event. But when we move the focus somewhere else, for instance, click on a button – there will be a change event:

For other elements: select , input type=checkbox/radio it triggers right after the selection changes:

 

Event: input

The input event triggers every time after a value is modified by the user.

Unlike keyboard events, it triggers on any value change, even those that does not involve keyboard actions: pasting with a mouse or using speech recognition to dictate the text.

If we want to handle every modification of an then this event is the best choice.

On the other hand, input event doesn’t trigger on keyboard input and other actions that do not involve value change, e.g. pressing arrow keys ⇦ ⇨ while in the input.

The input event occurs after the value is modified.

So we can’t use event.preventDefault() there – it’s just too late, there would be no effect.

Events: cut, copy, paste

These events occur on cutting/copying/pasting a value.

They belong to ClipboardEvent class and provide access to the data that is cut/copied/pasted.

We also can use event.preventDefault() to abort the action, then nothing gets copied/pasted.

For instance, the code below prevents all cut/copy/paste events and shows the text we’re trying to cut/copy/paste:

; input.oncut = input.oncopy = function(event) < alert(event.type + '-' + document.getSelection()); event.preventDefault(); >; 

Please note: inside cut and copy event handlers a call to event.clipboardData.getData(. ) returns an empty string. That’s because technically the data isn’t in the clipboard yet. If we use event.preventDefault() it won’t be copied at all.

So the example above uses document.getSelection() to get the selected text. You can find more details about document selection in the article Selection and Range.

It’s possible to copy/paste not just text, but everything. For instance, we can copy a file in the OS file manager, and paste it.

That’s because clipboardData implements DataTransfer interface, commonly used for drag’n’drop and copy/pasting. It’s a bit beyond our scope now, but you can find its methods in the DataTransfer specification.

Also, there’s an additional asynchronous API of accessing the clipboard: navigator.clipboard . More about it in the specification Clipboard API and events, not supported by Firefox.

Safety restrictions

The clipboard is a “global” OS-level thing. A user may switch between various applications, copy/paste different things, and a browser page shouldn’t see all that.

So most browsers allow seamless read/write access to the clipboard only in the scope of certain user actions, such as copying/pasting etc.

It’s forbidden to generate “custom” clipboard events with dispatchEvent in all browsers except Firefox. And even if we manage to dispatch such event, the specification clearly states that such “syntetic” events must not provide access to the clipboard.

Even if someone decides to save event.clipboardData in an event handler, and then access it later – it won’t work.

To reiterate, event.clipboardData works solely in the context of user-initiated event handlers.

On the other hand, navigator.clipboard is the more recent API, meant for use in any context. It asks for user permission, if needed.

Summary

Event Description Specials
change A value was changed. For text inputs triggers on focus loss.
input For text inputs on every change. Triggers immediately unlike change .
cut/copy/paste Cut/copy/paste actions. The action can be prevented. The event.clipboardData property gives access to the clipboard. All browsers except Firefox also support navigator.clipboard .

Tasks

Deposit calculator

Create an interface that allows to enter a sum of bank deposit and percentage, then calculates how much it will be after given periods of time.

Any input change should be processed immediately.

// initial: the initial money sum // interest: e.g. 0.05 means 5% per year // years: how many years to wait let result = Math.round(initial * (1 + interest) ** years);

Источник

HTMLElement: change event

The change event is fired for , , and elements when the user modifies the element’s value. Unlike the input event, the change event is not necessarily fired for each alteration to an element’s value .

Depending on the kind of element being changed and the way the user interacts with the element, the change event fires at a different moment:

Syntax

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

addEventListener("change", (event) => >); onchange = (event) => >; 

Event type

Examples

element

HTML

label> Choose an ice cream flavor: select class="ice-cream" name="ice-cream"> option value="">Select One …option> option value="chocolate">Chocolateoption> option value="sardine">Sardineoption> option value="vanilla">Vanillaoption> select> label> div class="result">div> 
body  display: grid; grid-template-areas: "select result"; > select  grid-area: select; > .result  grid-area: result; > 

JavaScript

const selectElement = document.querySelector(".ice-cream"); const result = document.querySelector(".result"); selectElement.addEventListener("change", (event) =>  result.textContent = `You like $event.target.value>`; >); 

Result

Text input element

For some elements, including , the change event doesn’t fire until the control loses focus. Try entering something into the field below, and then click somewhere else to trigger the event.

HTML

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

JavaScript

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

Result

Specifications

Browser compatibility

BCD tables only load in the browser

Different browsers do not always agree whether a change event should be fired for certain types of interaction. For example, keyboard navigation in elements used to never fire a change event in Gecko until the user hit Enter or switched the focus away from the (see Firefox bug 126379). Since Firefox 63 (Quantum), this behavior is consistent between all major browsers, however.

Found a content problem with this page?

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

Your blueprint for a better internet.

Источник

change

Это незавершённая статья. Вы можете помочь её закончить! Почитайте о том, как контрибьютить в Доку.

Кратко

Скопировать ссылку «Кратко» Скопировано

Событие change срабатывает, когда пользователь изменяет значение в , или и фиксирует свои изменения.

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

Как пишется

Скопировать ссылку «Как пишется» Скопировано

 const input = document.querySelector('.input') input.addEventListener('change', function (event)  console.log(event.target.value)>) const input = document.querySelector('.input') input.addEventListener('change', function (event)  console.log(event.target.value) >)      

Пример

Скопировать ссылку «Пример» Скопировано

💡 В зависимости от указанного типа в HTML элементе, change срабатывает по-разному. Лучше всего это становится понятным на примерах.

Как понять

Скопировать ссылку «Как понять» Скопировано

Подробнее о механизме событий читай в статье «Событийная модель».

Событие change похоже на события input и blur , но есть важные отличия:

blur – срабатывает каждый раз при расфокусировке поля.
input – срабатывает сразу же при изменении значения поля.
change – срабатывает когда значение поля изменено, но при условии снятия с него фокуса.

Источник

input

Input — событие, срабатывающее каждый раз при изменении значения.

Время чтения: меньше 5 мин

Кратко

Скопировать ссылку «Кратко» Скопировано

Событие input возникает, когда пользователь изменяет содержимое поля для ввода информации.

Событие input возникает когда DOM-дерево обновляется или вот-вот обновится. Если пользователь вставит текст из буфера обмена, то событие input возникнет один раз. Если же пользователь печатает текст, то событие input возникает после добавления (и удаления) каждого символа.

Простой пример

Скопировать ссылку «Простой пример» Скопировано

 Введите текст: При каждом изменении возникает событие input:   var inputTextField = document.getElementById('textField'); var outputTextField = document.getElementById('textResult'); inputTextField.oninput = function()  outputTextField.value = inputTextField.value; >;  label>Введите текст: input type="text" id="textField"> label> label>При каждом изменении возникает событие code>inputcode>: textarea disabled id="textResult">textarea> label> script> var inputTextField = document.getElementById('textField'); var outputTextField = document.getElementById('textResult'); inputTextField.oninput = function()  outputTextField.value = inputTextField.value; >; script>      

Как пишется

Скопировать ссылку «Как пишется» Скопировано

 const textInput = document.querySelector('input[type=text]'); function callback(evt)  console.log(`Произошло событие $`);> textInput.addEventListener('input', callback); /* Если теперь ввести в текстовое поле слово «Дока» и щёлкнуть вне этого поля, в консоли будут показаны сообщения: 4 раза: Произошло событие input*/ const textInput = document.querySelector('input[type=text]'); function callback(evt)  console.log(`Произошло событие $evt.type>`); > textInput.addEventListener('input', callback); /* Если теперь ввести в текстовое поле слово «Дока» и щёлкнуть вне этого поля, в консоли будут показаны сообщения: 4 раза: Произошло событие input */      

Отличие от события change

Скопировать ссылку «Отличие от события change» Скопировано

События input и change похожи — оба помогают отслеживать изменения в полях ввода.

Различие есть для текстовых полей ввода:

  • input — срабатывает при каждом изменении значения в поле;
  • change — срабатывает когда изменяемый элемент теряет фокус: например, при переходе к другому полю или клику на другую часть страницы.

Для прочих полей ввода они работают одинаково:

 Кликните: Типы событий:   const checkbox = document.querySelector('[name=checkbox-input]'); const textArea = document.querySelector('[name=checkbox-result]'); function handleCheckboxChange(evt)  textArea.value += evt.type + '; '; > checkbox.addEventListener('input', handleCheckboxChange); checkbox.addEventListener('change', handleCheckboxChange);  label>Кликните: input type="checkbox" name="checkbox-input"> label> label>Типы событий: textarea disabled name="checkbox-result">textarea> label> script> const checkbox = document.querySelector('[name=checkbox-input]'); const textArea = document.querySelector('[name=checkbox-result]'); function handleCheckboxChange(evt)  textArea.value += evt.type + '; '; > checkbox.addEventListener('input', handleCheckboxChange); checkbox.addEventListener('change', handleCheckboxChange); script>      

Примечания

Скопировать ссылку «Примечания» Скопировано

  • если текст не меняется, например при нажатиях клавиш влево ⇦ , вправо ⇨ , Control , Alt , Shift ;
  • если тег имеет атрибут type = «button» или type = «submit» ;
  • если поле изменит не пользователь, а код JS. Чтобы в этом случае получить событие input нужны дополнительные действия, например использовать dispatch Event ( ) .

Источник

Читайте также:  Php assoc array to index
Оцените статью