SlideShare a Scribd company logo
1 of 17
ФОРМЫ
МЕТОДЫ И СВОЙСТВА ЭЛЕМЕНТОВ
ФОРМЫ
ПСЕВДОМАССИВ
FORM.ELEMENTS
Элементы FORM можно получить по имени или номеру, используя
свойство document.forms[name/index].
Любой элемент формы form можно получить аналогичным образом,
используя свойство form.elements.
ПСЕВДОМАССИВ
FORM.ELEMENTS
Может быть несколько элементов с одинаковым именем. В таком случае
form.elements[name] вернет коллекцию элементов.
Ссылка на форму element.form
По элементу можно получить его форму, используя свойство element.form.
Пример:
ЭЛЕМЕНТ LABEL
Элемент label — один из самых важных в формах.
Клик на label засчитывается как фокусировка или клик на элементе формы,
к которому он относится.
Есть два способа показать, какой элемент относится к label:
ЭЛЕМЕНТЫ INPUT И TEXTAREA
Для большинства типов input значение ставится/читается через свойство
value.
Текущее «отмеченное» состояние для checkbox и radio находится в
свойстве checked (true/false).
ЭЛЕМЕНТЫ SELECT И OPTION
Селект в JavaScript можно установить двумя путями: поставив значение
select.value, либо установив свойство select.selectedIndex в номер нужной
опции.:
Установка selectedIndex = -1 очистит выбор.
Список элементов-опций доступен через select.options.
Если select допускает множественный выбор (атрибут multiple), то значения
можно получить/установить, сделав цикл по select.options. При этом
выбранные опции будут иметь свойство option.selected = true.
ЭЛЕМЕНТЫ SELECT И OPTION
new Option
Параметры:
text — содержимое,
value — значение,
defaultSelected и selected поставьте в true, чтобы сделать элемент
выбранным.
Его можно использовать вместо document.createElement('option'),
например:
Такой же элемент, но выбранный:
ЭЛЕМЕНТЫ SELECT И OPTION
Дополнительные свойства option
У элементов option также есть особые свойства, которые могут оказаться
полезными
selected
выбрана ли опция
index
номер опции в списке селекта
text
Текстовое содержимое опции (то, что видит посетитель).
ФОКУСИРОВКА: FOCUS/BLUR
События focus/blur
Событие focus вызывается тогда, когда пользователь фокусируется на
элементе, а blur — когда фокус исчезает
ФОКУСИРОВКА: FOCUS/BLUR
Методы focus/blur
Методы с теми же названиями переводят/уводят фокус с элемента.
ИЗМЕНЕНИЕ: CHANGE, INPUT,
CUT, COPY, PASTE
Событие change
Событие change происходит по окончании изменении значения элемента
формы, когда это изменение зафиксировано.
Для текстовых элементов это означает, что событие произойдёт не при
каждом вводе, а при потере фокуса.
Для остальных же элементов: select, input type=checkbox/radio оно
срабатывает сразу при выборе значения.
ИЗМЕНЕНИЕ: CHANGE, INPUT,
CUT, COPY, PASTE
Событие input
Событие input срабатывает тут же при изменении значения текстового
элемента и поддерживается всеми браузерами, кроме IE8-.
В IE9 оно поддерживается частично, а именно — не возникает при удалении
символов (как и onpropertychange).
IE10-, СОБЫТИЕ
PROPERTYCHANGE
Это событие происходит только в IE10-, при любом изменении свойства.
Оно позволяет отлавливать изменение тут же. Оно нестандартное, и его
основная область использования — исправление недочётов обработки
событий в старых IE.
Если поставить его на checkbox в IE8-, то получится «правильное»
событие change:
К сожалению, в IE9 у него недочёт: оно не срабатывает при удалении
символов. Поэтому сочетания onpropertychange + oninput недостаточно,
чтобы поймать любое изменение поля в старых IE.
IE10-, СОБЫТИЕ
PROPERTYCHANGE
ПРИМЕР: ПОЛЕ С
КОНТРОЛЕМ СМС
Событие input идеально решит задачу во всех браузерах, кроме IE9-.
Собственно, если IE9- нам не нужен, то на этом можно и остановиться.
IE9-
В IE8- событие input не поддерживается, но, как мы видели ранее, есть
onpropertychange, которое может заменить его.
Что же касается IE9 — там поддерживаются и input и onpropertychange, но
они оба не работают при удалении символов. Поэтому мы будем
отслеживать удаление при помощи keyup на Delete и BackSpace . А вот
удаление командой «вырезать» из меню — сможет отловить лишь oncut.
ПРИМЕР: ПОЛЕ С
КОНТРОЛЕМ СМС
Здесь мы добавили вызов showCount на все события, которые могут
приводить к изменению значения. Да, иногда изменение будет
обрабатываться несколько раз, но зато с гарантией.
ПРИМЕР: ПОЛЕ С
КОНТРОЛЕМ СМС
Чтобы сэкономить ресурсы браузера, мы можем начинать отслеживание по
onfocus, а прекращать — по onblur, вот так:

More Related Content

Featured

How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Applitools
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at WorkGetSmarter
 

Featured (20)

How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work
 
ChatGPT webinar slides
ChatGPT webinar slidesChatGPT webinar slides
ChatGPT webinar slides
 

Module 5

  • 1. ФОРМЫ МЕТОДЫ И СВОЙСТВА ЭЛЕМЕНТОВ ФОРМЫ
  • 2. ПСЕВДОМАССИВ FORM.ELEMENTS Элементы FORM можно получить по имени или номеру, используя свойство document.forms[name/index]. Любой элемент формы form можно получить аналогичным образом, используя свойство form.elements.
  • 3. ПСЕВДОМАССИВ FORM.ELEMENTS Может быть несколько элементов с одинаковым именем. В таком случае form.elements[name] вернет коллекцию элементов. Ссылка на форму element.form По элементу можно получить его форму, используя свойство element.form. Пример:
  • 4. ЭЛЕМЕНТ LABEL Элемент label — один из самых важных в формах. Клик на label засчитывается как фокусировка или клик на элементе формы, к которому он относится. Есть два способа показать, какой элемент относится к label:
  • 5. ЭЛЕМЕНТЫ INPUT И TEXTAREA Для большинства типов input значение ставится/читается через свойство value. Текущее «отмеченное» состояние для checkbox и radio находится в свойстве checked (true/false).
  • 6. ЭЛЕМЕНТЫ SELECT И OPTION Селект в JavaScript можно установить двумя путями: поставив значение select.value, либо установив свойство select.selectedIndex в номер нужной опции.: Установка selectedIndex = -1 очистит выбор. Список элементов-опций доступен через select.options. Если select допускает множественный выбор (атрибут multiple), то значения можно получить/установить, сделав цикл по select.options. При этом выбранные опции будут иметь свойство option.selected = true.
  • 7. ЭЛЕМЕНТЫ SELECT И OPTION new Option Параметры: text — содержимое, value — значение, defaultSelected и selected поставьте в true, чтобы сделать элемент выбранным. Его можно использовать вместо document.createElement('option'), например: Такой же элемент, но выбранный:
  • 8. ЭЛЕМЕНТЫ SELECT И OPTION Дополнительные свойства option У элементов option также есть особые свойства, которые могут оказаться полезными selected выбрана ли опция index номер опции в списке селекта text Текстовое содержимое опции (то, что видит посетитель).
  • 9. ФОКУСИРОВКА: FOCUS/BLUR События focus/blur Событие focus вызывается тогда, когда пользователь фокусируется на элементе, а blur — когда фокус исчезает
  • 10. ФОКУСИРОВКА: FOCUS/BLUR Методы focus/blur Методы с теми же названиями переводят/уводят фокус с элемента.
  • 11. ИЗМЕНЕНИЕ: CHANGE, INPUT, CUT, COPY, PASTE Событие change Событие change происходит по окончании изменении значения элемента формы, когда это изменение зафиксировано. Для текстовых элементов это означает, что событие произойдёт не при каждом вводе, а при потере фокуса. Для остальных же элементов: select, input type=checkbox/radio оно срабатывает сразу при выборе значения.
  • 12. ИЗМЕНЕНИЕ: CHANGE, INPUT, CUT, COPY, PASTE Событие input Событие input срабатывает тут же при изменении значения текстового элемента и поддерживается всеми браузерами, кроме IE8-. В IE9 оно поддерживается частично, а именно — не возникает при удалении символов (как и onpropertychange).
  • 13. IE10-, СОБЫТИЕ PROPERTYCHANGE Это событие происходит только в IE10-, при любом изменении свойства. Оно позволяет отлавливать изменение тут же. Оно нестандартное, и его основная область использования — исправление недочётов обработки событий в старых IE. Если поставить его на checkbox в IE8-, то получится «правильное» событие change: К сожалению, в IE9 у него недочёт: оно не срабатывает при удалении символов. Поэтому сочетания onpropertychange + oninput недостаточно, чтобы поймать любое изменение поля в старых IE.
  • 15. ПРИМЕР: ПОЛЕ С КОНТРОЛЕМ СМС Событие input идеально решит задачу во всех браузерах, кроме IE9-. Собственно, если IE9- нам не нужен, то на этом можно и остановиться. IE9- В IE8- событие input не поддерживается, но, как мы видели ранее, есть onpropertychange, которое может заменить его. Что же касается IE9 — там поддерживаются и input и onpropertychange, но они оба не работают при удалении символов. Поэтому мы будем отслеживать удаление при помощи keyup на Delete и BackSpace . А вот удаление командой «вырезать» из меню — сможет отловить лишь oncut.
  • 16. ПРИМЕР: ПОЛЕ С КОНТРОЛЕМ СМС Здесь мы добавили вызов showCount на все события, которые могут приводить к изменению значения. Да, иногда изменение будет обрабатываться несколько раз, но зато с гарантией.
  • 17. ПРИМЕР: ПОЛЕ С КОНТРОЛЕМ СМС Чтобы сэкономить ресурсы браузера, мы можем начинать отслеживание по onfocus, а прекращать — по onblur, вот так: