- How to Get The Text Input Value Using JavaScript Events
- How to Get The Value From Text Input Using JavaScript
- Using change Event to Get The Value From Input
- Using input Event to Get The Value From Input
- Can We Use keydown or keyup Events to Get Input Value?
- Conclusion
- HTMLElement: input event
- Syntax
- Event type
- Examples
- HTML
- JavaScript
- Result
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- События: change, input, cut, copy, paste
- Событие: change
- Событие: input
- События: cut, copy, paste
- Итого
- Задачи
- Депозитный калькулятор
How to Get The Text Input Value Using JavaScript Events
The input field has a value property to get the input value in JavaScript. You can use different events to extract the value in order to run data validation and send it to the server.
The main purpose of using HTML input fields is to collect information from users and utilize them in the application. That’s why it is important to know different ways to collect values from HTML input fields using JavaScript.
I will also try to explain which is the most optimal way for us in most cases. But you are free to use any of the methods discussed below.
How to Get The Value From Text Input Using JavaScript
When we add a field in our HTML file, we also add some attributes to it. Like, the type attribute represents the type of our input field.
I am creating a text input but you can have a different type of field. It doesn’t matter process will be the same.
This input field has an username id. I will use this id value in JavaScript to get the reference object of the field. Every input object has a value property that returns the value.
const username = document.getElementById('username'); console.log(username.value);
But we need to get the value whenever a user enters something in our field. For that, you can use JavaScript events. We can also get the input value on a button click if you want.
These are the following events that we can use to collect values from input fields in JavaScript:
Using change Event to Get The Value From Input
When we listen to the change event on our field, JavaScript only fires off this event when a user changes the input value and removes the focus from the field.
That means when you are typing inside the field, this event will not do anything. Whenever you complete typing and lose focus from the field by clicking anywhere else then it executes.
const username = document.getElementById('username'); // Using change event username.addEventListener('change', () => < console.log(username.value); >);
This is the most used JavaScript event for getting input values. Because this event callback function will not run every time a user types a character. Rather it will execute once when a user is done typing.
In addition to that, when you focus on the field and leave it without changing the current value, this callback function will not run. That means it executes only when the input value changes.
That’s why it is great in the case of performance and data validation. It also works if you copy a text and paste it inside the field.
Most of the time, this is what we really need in our application. But if you want to validate the input value every time a user types something, you can use the input event for that.
Using input Event to Get The Value From Input
JavaScript triggers the input event when someone enters a value in the field. We don’t have to leave the field. Every time we enter or remove something from the field, this event will fire off.
This is the main difference between input and change events in JavaScript. This event is useful in some situations. For example, we can use it for password validation.
When anyone starts entering a password, you can validate whether it qualifies for the requirement like length, numbers, special characters, etc.
const username = document.getElementById('username'); // Using input event username.addEventListener('input', () => < console.log(username.value); >);
Listen to the input event on the username field and access the value inside the callback function with username.value property. This callback function will also execute if you copy and paste text in the input field.
Can We Use keydown or keyup Events to Get Input Value?
There are other events like keydown and keyup in JavaScript, but these are not great for getting value from the field.
If we use keydown event for our username input field, the callback function will run for any key press. Whenever users press a key on their keyboard, this function will execute.
const username = document.getElementById('username'); // Using input event username.addEventListener('keydown', () => < console.log(username.value); >);
There are some problems with this event. Any key can trigger this event. Like, if you press the shift or ctrl key, this event will fire off. But these keys don’t change the input value.
Another problem is that when this callback function executes, we don’t get the updated value from username.value property. We get the previous value.
Because JavaScript fires this event even before updating the value property. That’s why this event is mostly suitable for getting an immediate response from any key press like creating keyboard shortcuts in JavaScript.
const username = document.getElementById('username'); // Using input event username.addEventListener('keyup', () => < console.log(username.value); >);
The keyup event is almost similar to the keydown event in JavaScript. This event gets fired off when we press any key and release it from our keyboard.
If you press a key and hold it, this event will not do anything. This is the main difference between these 2 JavaScript events.
Another thing is if you use keyup event with the username input field, you will get the updated value from it. Unlike the keydown event, this event updates the value property before executing the callback function.
Conclusion
In this article, I have discussed 4 JavaScript events. Among them, we should not use keydown and keyup events for their limitations. That’s why you can consider the other two depending on the situation.
If you want to get the input value every time users change the value, you should use the input event. But if you want to extract the value after changing and leaving the field, you will apply the change event.
I hope you have understood the differences between these events. Now you can choose any of these events to get the value from an input field in JavaScript.
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);