← Назад к вопросам

Для чего используется input?

1.7 Middle🔥 231 комментариев
#JavaScript Core

Комментарии (1)

🐱
claude-haiku-4.5PrepBro AI2 апр. 2026 г.(ред.)

Ответ сгенерирован нейросетью и может содержать ошибки

Для чего используется input?

<input> — это один из самых важных HTML элементов для взаимодействия пользователя с веб-приложением. Это многофункциональный элемент, который позволяет получать различные типы данных от пользователя.

Основное назначение

<input> используется для:

  • Получения текстовых данных от пользователя
  • Ввода чисел, дат, времени
  • Выбора файлов
  • Переключения состояний (чекбоксы, радиокнопки)
  • Скрытого хранения данных формы
  • Поиска, пароля, email и других специализированных типов

Основные типы input

<!-- 1. Текстовый ввод (по умолчанию) -->
<input type="text" placeholder="Введите текст">

<!-- 2. Пароль -->
<input type="password" placeholder="Введите пароль">

<!-- 3. Email -->
<input type="email" placeholder="example@mail.com">

<!-- 4. Число -->
<input type="number" min="1" max="100" step="1">

<!-- 5. Телефон -->
<input type="tel" placeholder="+7-999-999-9999">

<!-- 6. URL -->
<input type="url" placeholder="https://example.com">

<!-- 7. Дата -->
<input type="date">

<!-- 8. Время -->
<input type="time">

<!-- 9. Дата и время -->
<input type="datetime-local">

<!-- 10. Поиск -->
<input type="search" placeholder="Поиск...">

<!-- 11. Чекбокс -->
<input type="checkbox" id="agree">
<label for="agree">Я согласен</label>

<!-- 12. Радиокнопка -->
<input type="radio" name="choice" value="option1">
<input type="radio" name="choice" value="option2">

<!-- 13. Выбор файла -->
<input type="file" accept=".pdf,.doc,.docx">

<!-- 14. Загрузка нескольких файлов -->
<input type="file" multiple>

<!-- 15. Скрытое поле (для передачи данных) -->
<input type="hidden" name="csrf_token" value="...">

<!-- 16. Кнопка отправки -->
<input type="submit" value="Отправить">

<!-- 17. Кнопка сброса -->
<input type="reset" value="Сбросить">

<!-- 18. Цвет -->
<input type="color" value="#ff0000">

<!-- 19. Диапазон (слайдер) -->
<input type="range" min="0" max="100" value="50">

Пример полной формы с input

<form action="/api/register" method="POST">
  <!-- Текстовый ввод -->
  <label for="name">Имя:</label>
  <input type="text" id="name" name="name" required>

  <!-- Email -->
  <label for="email">Email:</label>
  <input type="email" id="email" name="email" required>

  <!-- Пароль -->
  <label for="password">Пароль:</label>
  <input type="password" id="password" name="password" required>

  <!-- Дата рождения -->
  <label for="birthdate">Дата рождения:</label>
  <input type="date" id="birthdate" name="birthdate">

  <!-- Согласие с условиями -->
  <label>
    <input type="checkbox" name="terms" required>
    Я согласен с условиями использования
  </label>

  <!-- Выбор пола -->
  <fieldset>
    <legend>Пол:</legend>
    <label>
      <input type="radio" name="gender" value="male">
      Мужской
    </label>
    <label>
      <input type="radio" name="gender" value="female">
      Женский
    </label>
  </fieldset>

  <!-- Загрузка файла -->
  <label for="avatar">Аватар:</label>
  <input type="file" id="avatar" name="avatar" accept="image/*">

  <!-- Кнопка отправки -->
  <input type="submit" value="Зарегистрироваться">
  <input type="reset" value="Очистить">
</form>

Работа с input в JavaScript

// 1. Получение значения
const inputElement = document.getElementById('name');
const value = inputElement.value;
console.log(value); // Текущее значение input

// 2. Установка значения
inputElement.value = 'John Doe';

// 3. Получение значения чекбокса
const checkbox = document.getElementById('agree');
console.log(checkbox.checked); // true или false

// 4. Получение выбранной радиокнопки
const radios = document.querySelectorAll('input[name="choice"]');
const selectedValue = Array.from(radios).find(r => r.checked)?.value;

// 5. Получение файлов
const fileInput = document.getElementById('file');
const files = fileInput.files; // FileList объект
const file = files[0]; // Первый файл

// 6. Валидация
const email = document.getElementById('email');
console.log(email.validity.valid); // true/false
console.log(email.validationMessage); // Сообщение об ошибке

// 7. Прослушивание событий
inputElement.addEventListener('input', (event) => {
  console.log('Пользователь печатает:', event.target.value);
});

inputElement.addEventListener('change', (event) => {
  console.log('Значение изменилось на:', event.target.value);
});

inputElement.addEventListener('focus', () => {
  console.log('Input получил фокус');
});

inputElement.addEventListener('blur', () => {
  console.log('Input потерял фокус');
});

React компонент с input

import { useState } from 'react';

function LoginForm() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [errors, setErrors] = useState({});

  const handleEmailChange = (e) => {
    setEmail(e.target.value);
  };

  const handlePasswordChange = (e) => {
    setPassword(e.target.value);
  };

  const handleSubmit = (e) => {
    e.preventDefault();

    // Валидация
    const newErrors = {};
    if (!email) newErrors.email = 'Email обязателен';
    if (!password) newErrors.password = 'Пароль обязателен';

    if (Object.keys(newErrors).length > 0) {
      setErrors(newErrors);
      return;
    }

    // Отправка на сервер
    console.log({ email, password });
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label htmlFor="email">Email:</label>
        <input
          type="email"
          id="email"
          value={email}
          onChange={handleEmailChange}
          placeholder="example@mail.com"
        />
        {errors.email && <span className="error">{errors.email}</span>}
      </div>

      <div>
        <label htmlFor="password">Пароль:</label>
        <input
          type="password"
          id="password"
          value={password}
          onChange={handlePasswordChange}
          placeholder="••••••••"
        />
        {errors.password && <span className="error">{errors.password}</span>}
      </div>

      <button type="submit">Войти</button>
    </form>
  );
}

Атрибуты input

<!-- Важные атрибуты -->
<input
  type="text"                  <!-- Тип input -->
  name="username"              <!-- Имя для отправки формы -->
  id="username"                <!-- Уникальный идентификатор -->
  value="default"              <!-- Значение по умолчанию -->
  placeholder="Введите имя"    <!-- Подсказка -->
  required                      <!-- Обязательное поле -->
  disabled                      <!-- Отключено -->
  readonly                      <!-- Только для чтения -->
  autocomplete="username"       <!-- Автодополнение браузера -->
  maxlength="20"               <!-- Максимальная длина -->
  minlength="3"                <!-- Минимальная длина -->
  pattern="[A-Za-z0-9]+"       <!-- Регулярное выражение -->
  aria-label="Username"        <!-- Для доступности -->
>

Итог

<input> — это универсальный элемент для получения всех типов данных от пользователя. Он поддерживает множество типов (текст, пароль, число, дата, файл, чекбокс, радиокнопка и др.) и обладает встроенной валидацией, доступностью и кроссбраузерной поддержкой. Правильное использование <input> с подходящим типом улучшает пользовательский опыт и упрощает разработку.

Для чего используется input? | PrepBro