- Изменение: change, input, cut, copy, paste
- Событие change
- Событие input
- IE10-, событие propertychange
- События cut, copy, paste
- Пример: поле с контролем СМС
- IE9-
- Итого
- Задачи
- Автовычисление процентов по вкладу
- Комментарии
- Javascript Change HTML Element Text Tutorial
- How to change an element’s text content
- How to change an element’s innerHTML
- The innerText property
- Which text property should you use
- Summary: Points to remember
- JavaScript HTML DOM — Changing HTML
- Changing HTML Content
- Example
- Example
- Changing the Value of an Attribute
- Example
- Dynamic HTML content
- Example
- document.write()
- Example
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- Change Text in p tag JavaScript | Easy HTML example code
- Example Change Text in p tag JavaScript
- Q: How to change the text inside onClick ?
- Explanation
Изменение: change, input, cut, copy, paste
Материал на этой странице устарел, поэтому скрыт из оглавления сайта.
Более новая информация по этой теме находится на странице https://learn.javascript.ru/events-change-input.
На элементах формы происходят события клавиатуры и мыши, но есть и несколько других, особенных событий.
Событие change
Событие change происходит по окончании изменения значения элемента формы, когда это изменение зафиксировано.
Для текстовых элементов это означает, что событие произойдёт не при каждом вводе, а при потере фокуса.
Например, пока вы набираете что-то в текстовом поле ниже – события нет. Но как только вы уведёте фокус на другой элемент, например, нажмёте кнопку – произойдёт событие onchange .
Для остальных же элементов: select , input type=checkbox/radio оно срабатывает сразу при выборе значения.
В IE8- checkbox/radio при изменении мышью не инициируют событие сразу, а ждут потери фокуса.
Для того, чтобы видеть изменения checkbox/radio тут же – в IE8- нужно повесить обработчик на событие click (оно произойдёт и при изменении значения с клавиатуры) или воспользоваться событием propertychange , описанным далее.
Событие input
Событие input срабатывает тут же при изменении значения текстового элемента и поддерживается всеми браузерами, кроме IE8-.
В IE9 оно поддерживается частично, а именно – не возникает при удалении символов (как и onpropertychange ).
Пример использования (не работает в IE8-):
В современных браузерах oninput – самое главное событие для работы с элементом формы. Именно его, а не keydown/keypress следует использовать.
Если бы ещё не проблемы со старыми IE… Впрочем, их можно решить при помощи события propertychange .
IE10-, событие propertychange
Это событие происходит только в IE10-, при любом изменении свойства. Оно позволяет отлавливать изменение тут же. Оно нестандартное, и его основная область использования – исправление недочётов обработки событий в старых IE.
Если поставить его на checkbox в IE8-, то получится «правильное» событие change :
Чекбокс с "onchange", работающим везде одинаково
Это событие также срабатывает при изменении значения текстового элемента. Поэтому его можно использовать в старых IE вместо oninput .
К сожалению, в IE9 у него недочёт: оно не срабатывает при удалении символов. Поэтому сочетания onpropertychange + oninput недостаточно, чтобы поймать любое изменение поля в старых IE. Далее мы рассмотрим пример, как это можно сделать иначе.
События cut, copy, paste
Эти события используются редко. Они происходят при вырезании/вставке/копировании значения.
К сожалению, кросс-браузерного способа получить данные, которые вставляются/копируются, не существует, поэтому их основное применение – это отмена соответствующей операции.
Пример: поле с контролем СМС
Как видим, событий несколько и они взаимно дополняют друг друга.
Посмотрим, как их использовать, на примере.
Сделаем поле для СМС, рядом с которым должно показываться число символов, обновляющееся при каждом изменении поля.
Событие input идеально решит задачу во всех браузерах, кроме IE9-. Собственно, если IE9- нам не нужен, то на этом можно и остановиться.
IE9-
В IE8- событие input не поддерживается, но, как мы видели ранее, есть onpropertychange , которое может заменить его.
Что же касается IE9 – там поддерживаются и input и onpropertychange , но они оба не работают при удалении символов. Поэтому мы будем отслеживать удаление при помощи keyup на Delete и BackSpace . А вот удаление командой «вырезать» из меню – сможет отловить лишь oncut .
Получается вот такая комбинация:
sms.onkeyup = sms.oninput = showCount; sms.onpropertychange = function() < if (event.propertyName == "value") showCount(); >sms.oncut = function() < setTimeout(showCount, 0); // на момент oncut значение ещё старое >;
Здесь мы добавили вызов showCount на все события, которые могут приводить к изменению значения. Да, иногда изменение будет обрабатываться несколько раз, но зато с гарантией. А лишние вызовы легко убрать, например, при помощи throttle -декоратора, описанного в задаче Тормозящий (throttling) декоратор.
Есть и совсем другой простой, но действенный вариант: через setInterval регулярно проверять значение и, если оно слишком длинное, обрезать его.
Чтобы сэкономить ресурсы браузера, мы можем начинать отслеживание по onfocus , а прекращать – по onblur , вот так:
>, 20); >; sms.onblur = function() < clearInterval(timerId); >; function showCount()
Обратим внимание – весь этот «танец с бубном» нужен только для поддержки IE8-, в которых не поддерживается oninput и IE9, где oninput не работает при удалении.
Итого
Событие | Описание | Особенности |
---|---|---|
change | Изменение значения любого элемента формы. Для текстовых элементов срабатывает при потере фокуса. | В IE8- на чекбоксах ждёт потери фокуса, поэтому для мгновенной реакции ставят также onclick -обработчик или onpropertychange . |
input | Событие срабатывает только на текстовых элементах. Оно не ждёт потери фокуса, в отличие от change . | В IE8- не поддерживается, в IE9 не работает при удалении символов. |
propertychange | Только для IE10-. Универсальное событие для отслеживания изменения свойств элементов. Имя изменённого свойства содержится в event.propertyName . Используют для мгновенной реакции на изменение значения в старых IE. | В IE9 не срабатывает при удалении символов. |
cut/copy/paste | Срабатывают при вставке/копировании/удалении текста. Если в их обработчиках отменить действие браузера, то вставки/копирования/удаления не произойдёт. | Вставляемое значение получить нельзя: на момент срабатывания события в элементе всё ещё старое значение, а новое недоступно. |
Ещё особенность: в IE8- события change , propertychange , cut и аналогичные не всплывают. То есть, обработчики нужно назначать на сам элемент, без делегирования.
Задачи
Автовычисление процентов по вкладу
Создайте интерфейс для автоматического вычисления процентов по вкладу.
Ставка фиксирована: 12% годовых. При включённом поле «капитализация» – проценты приплюсовываются к сумме вклада каждый месяц (сложный процент).
- В поле с суммой должно быть нельзя ввести не-цифру. При этом пусть в нём работают специальные клавиши и сочетания Ctrl-X/Ctrl-V.
- Изменения в форме отражаются в результатах сразу.
Только численный ввод в поле с суммой разрешаем, повесив обработчик на keypress .
Отслеживаем события изменения для перевычисления результатов:
- На input : событие input и дополнительно propertychange/keyup для совместимости со старыми IE.
- На checkbox : событие click вместо change для совместимости с IE8-.
- На select : событие change .
Комментарии
- Если вам кажется, что в статье что-то не так — вместо комментария напишите на GitHub.
- Для одной строки кода используйте тег , для нескольких строк кода — тег , если больше 10 строк — ссылку на песочницу (plnkr, JSBin, codepen…)
- Если что-то непонятно в статье — пишите, что именно и с какого места.
Javascript Change HTML Element Text Tutorial
In this Javascipt tutorial we learn how to return and change text, or HTML content, within an element.
We also discuss the differences between the innerText, innerHTML and textContent properties and which one we should use.
How to change an element’s text content
Javascript provides us with the textContent property that we can use to change the text inside an element.
When we change the value of the property, it will completely overwrite the previous value.
This property will only return the text inside an element. Any HTML inside the element will be stripped before the text is returned.
If we run the example above, we can see the formatting that’s present in the top paragraph is no longer there in the bottom paragraph.
This means we cannot use textContent to replace text with something that includes html.
If we run the example above, it will print the HTML code instead of creating a link.
How to change an element’s innerHTML
Javascript also provides us with the innerHTML property that we can use to change the text inside an element.
Unlike the textContent property, innerHTML will return everything exactly as it is inside the element, including HTML.
This time the second paragraph has all its formatting and the link is still available because innerHTML brings any HTML along.
This means that we can include HTML elements when replacing text.
In the example above, the link is generated instead of displaying the code.
The innerText property
The innerText property works the same as the textContent property but will not return any hidden elements.
If we run the example above, we can see that innerText doesn’t display the hidden element.
Both innerText and textContent will display content inside or tags.
The only difference is that innerText will keep the formatting, whereas textContent will not.
Which text property should you use
It depends on your situation. If you simply want to change the text in an element, any of these properties will work.
- If you want to return or change the HTML inside an element, use innerHTML.
- If you want to return or change just the text inside an element, use innerText.
- If you want to return or change just the text inside hidden elements, use textContent.
Summary: Points to remember
- We can use the innerHTML, innerText and textContent properties to return or change text inside an element.
- The textContent property will return all text, including anything inside a hidden element.
- The innerText property will return all text, excluding anything inside a hidden element.
- The innerHTML property will return both text and any other HTML content inside the element.
JavaScript HTML DOM — Changing HTML
The HTML DOM allows JavaScript to change the content of HTML elements.
Changing HTML Content
The easiest way to modify the content of an HTML element is by using the innerHTML property.
To change the content of an HTML element, use this syntax:
This example changes the content of a
element:
Example
- The HTML document above contains a
element with id=»p1″
- We use the HTML DOM to get the element with id=»p1″
- A JavaScript changes the content ( innerHTML ) of that element to «New text!»
This example changes the content of an element:
Example
- The HTML document above contains an element with id=»id01″
- We use the HTML DOM to get the element with id=»id01″
- A JavaScript changes the content ( innerHTML ) of that element to «New Heading»
Changing the Value of an Attribute
To change the value of an HTML attribute, use this syntax:
This example changes the value of the src attribute of an element:
Example
- The HTML document above contains an element with id=»myImage»
- We use the HTML DOM to get the element with id=»myImage»
- A JavaScript changes the src attribute of that element from «smiley.gif» to «landscape.jpg»
Dynamic HTML content
JavaScript can create dynamic HTML content:
Example
document.write()
In JavaScript, document.write() can be used to write directly to the HTML output stream:
Example
Never use document.write() after the document is loaded. It will overwrite the document.
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.
Change Text in p tag JavaScript | Easy HTML example code
Find the element by id and use the innerText attribute to Change Text in p tag in JavaScript. By this approach, you can change the text dynamically based on the conditions.
Example Change Text in p tag JavaScript
HTML example code change p tag text even it’s inside a div tag in JS.
Hello Wrold!
Q: How to change the text inside
onClick ?
Answer: Same as above example with using a code inside the function. The function will Tigger on clicking a button.
Sample paragraph.
I am sample paragraph.
function change_text()Explanation
- Here id_name is the id of the HTML tag to identify it.
- innerHTML is used to change the text inside the selected HTML tag using the document.getElementById() method.
- change_text() is function name.
Do comment if you have any doubts and suggestions on this topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version