- JavaScript change Event
- Using JavaScript change event for input elements
- Using JavaScript change event for radio buttons
- Using JavaScript change event for checkboxes
- Using JavaScript change event for the select element
- Summary
- События Формы
- Событие отправки формы
- Очистка полей формы
- Невалидность полей формы
- События input, textarea
- События select
- События checkbox / radio
- События range
- HTML DOM Input Radio Object
- Access an Input Radio Object
- Example
- Create an Input Radio Object
- Example
- Input Radio Object Properties
- Standard Properties and Events
- Related Pages
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
JavaScript change Event
Summary: in this tutorial, you’ll learn about the JavaScript change event of the input text, radio button, checkbox, and select elements.
The change event occurs when the element has completed changing.
To attach an event handler to the change event of an element, you can either call the addEventListener() method:
element.addEventListener('change', function( )< // handle change >);
Code language: JavaScript (javascript)
or use the onchange attribute of the element. For example:
input type="text" onchange="changeHandler()">
Code language: HTML, XML (xml)
However, it is a good practice to use the addEventListener() method.
Using JavaScript change event for input elements
The change event of an element fires when the element loses focus. The change event does not fire when you’re tying.
The following example shows the value of the input text when it loses focus.
html>
html lang="en"> head> meta charset="UTF-8"> meta name="viewport" content="width=device-width, initial-scale=1.0"> title>JavaScript change Event for Input Element title> head> body> label for="message">Message: label> input type="text" class="input" id="message" name="message"> button>Submit button> p id="result"> p> script> let input = document.querySelector('.input'); let result = document.querySelector('#result'); input.addEventListener('change', function ( ) < result.textContent = this.value; >); script> body> html>Code language: HTML, XML (xml)
In this example, if you type some text on the element and move focus to the button, the change event fires to show the entered text.
Note that if you want to handle every change of the value, you use the input event instead.
Using JavaScript change event for radio buttons
A radio button fires the change event after you select it.
The following example shows how to handle the change event of the radio buttons:
html>
html lang="en"> head> meta charset="UTF-8"> meta name="viewport" content="width=device-width, initial-scale=1.0"> title>JavaScript change Event for Radio Buttons title> head> body> span>Status: span> input type="radio" id="pending" name="status"> label for="pending">Pending label> input type="radio" id="resolved" name="status"> label for="resolved">Resolved label> input type="radio" id="rejected" name="status"> label for="rejected">Rejected label> p id="result"> p> script> let result = document.querySelector('#result'); document.body.addEventListener('change', function (e) < let target = e.target; let message; switch (target.id) < case 'pending': message = 'The Pending radio button changed'; break; case 'resolved': message = 'The Resolved radio button changed'; break; case 'rejected': message = 'The Rejected radio button changed'; break; > result.textContent = message; >); script> body> html>Code language: HTML, XML (xml)
- First, register an event handler to the change event of the body . When a radio button is clicked, its change event is bubbled to the body. This technique is called event delegation.
- Then, show a corresponding message based on which radio button is selected.
Using JavaScript change event for checkboxes
Similar to radio buttons, checkboxes fire the change event after selection, whether checked or unchecked. For example:
html>
html lang="en"> head> meta charset="UTF-8"> meta name="viewport" content="width=device-width, initial-scale=1.0"> title>JavaScript change Event for Checkboxes title> head> body> label for="status">Web Technology: label> input type="checkbox" id="html"> HTML input type="checkbox" id="css"> CSS input type="checkbox" id="js"> JavaScript p id="result"> p> script> let result = document.querySelector('#result'); document.body.addEventListener('change', function (e) < let target = e.target; let message; switch (target.id) < case 'html': message = 'The HTML checkbox changed'; break; case 'css': message = 'The CSS checkbox changed'; break; case 'js': message = 'The JavaScript checkbox changed'; break; > result.textContent = message; >); script> body> html>Code language: HTML, XML (xml)
Using JavaScript change event for the select element
The element fires the change event once the selection has completed.
The following example shows how to handle the change event of the element. The
element with the id result will display the selected item:
html>
html lang="en"> head> meta charset="UTF-8"> meta name="viewport" content="width=device-width, initial-scale=1.0"> title>JavaScript change Event for Select element title> head> body> select id="lang"> option value="">Select a language option> option value="JavaScript">JavaScript option> option value="TypeScript">TypeScript option> option value="PHP">PHP option> option value="Python">Python option> option value="Java">Java option> select> p id="result"> p> script> let select = document.querySelector('#lang'); let result = document.querySelector('#result'); select.addEventListener('change', function ( ) < result.textContent = this.value; >); script> body> html>Code language: HTML, XML (xml)
- First, select the element by its id ( lang );
- Then, show the selected value in the
element.
Summary
- The element fires the change event once it loses focus.
- The radio button, checkbox, and select elements fire the change event after they have been selected.
События Формы
Рассмотрим основные события форм: отправка формы, очистка полей, фокус элемента формы, потеря фокуса, события для input, select, checkbox и многое другое.
Событие отправки формы
Слушать событие отправки формы можно при помощи submit .
Чтобы поймать событие отправки формы, используйте submit .
my_form.addEventListener("submit", () => < console.log("Событие отправки формы") >)
Очистка полей формы
Событие очистки полей формы.
my_form.addEventListener("reset", () => < console.log("Событие очистки полей формы") >)
Метод для очистки полей формы.
Невалидность полей формы
Событие invalid срабатывает при попытке отправить форму, когда одно или несколько полей формы неверно заполнены. Или не заполнены, когда поле имеет атрибут required .
my_form.addEventListener("invalid", (e) => < console.log("Значения формы не валидны"); >, true)
Как реализовать проверку правильности ввода данных, можете прочитать в статье про валидацию input.
События input, textarea
На input и textarea можно слушать следующие события:
- input — событие ввода
- change — событие изменения input (срабатывает после изменения поля и потери фокуса);
- focus — выбор элемента, фокус;
- blur — потеря фокуса;
- select — выделение текста;
- keyup — событие отпускание кнопки;
- contextmenu — правый щелчок мыши.
const inputs = document.querySelectorAll(".form-events input"); inputs.forEach(el => < el.addEventListener("change", function () < // ваш код >) >);
Посмотреть когда срабатывают основные события форм, можете ниже.
События select
Для элемента select можем отслеживать следующие события:
- change — выбор элемента из списка (option);
- focus — фокус на select;
- blur — потеря фокуса select.
my_select.addEventListener("change", () => console.log("Выбран пункт из списка select"));
В примере ниже посмотрите, когда какие события срабатывают для элемента формы select .
Если вам интересно как стилизуется select, вот ссылка на статью.
События checkbox / radio
Для checkbox / radio можно использовать следующие события:
checkb.addEventListener("change", () => console.log(checkb.value)); radio.addEventListener("click", () => console.log(radio.value));
Здесь вам пригодятся знания, как проверить состояние чекбокса.
События range
Для input type range используют следующие события:
- change — происходит в момент отпускания кнопки;
- input — происходит в режиме реального времени.
range.addEventListener("change", () => console.log(range.value));
HTML DOM Input Radio Object
The Input Radio object represents an HTML element with type=»radio».
Access an Input Radio Object
You can access an element with type=»radio» by using getElementById():
Example
Tip: You can also access by searching through the elements collection of a form.
Create an Input Radio Object
You can create an element with type=»radio» by using the document.createElement() method:
Example
Input Radio Object Properties
Property | Description |
---|---|
autofocus | Sets or returns whether a radio button should automatically get focus when the page loads |
checked | Sets or returns the checked state of a radio button |
defaultChecked | Returns the default value of the checked attribute |
defaultValue | Sets or returns the default value of a radio button |
disabled | Sets or returns whether the radio button is disabled, or not |
form | Returns a reference to the form that contains the radio button |
name | Sets or returns the value of the name attribute of a radio button |
required | Sets or returns whether the radio button must be checked before submitting a form |
type | Returns which type of form element the radio button is |
value | Sets or returns the value of the value attribute of the radio button |
Standard Properties and Events
The Input Radio object also supports the standard properties and events.
Related Pages
COLOR PICKER
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.