\n```\n\n### Как сделать форму фокусируемой\n\n#### Вариант 1: Добавить tabindex\n\n```html\n
\n \n \n \n
\n\n\n```\n\n**Значения tabindex:**\n- `tabindex=\"-1\"` — элемент фокусируется программно, но НЕ через Tab\n- `tabindex=\"0\"` — элемент получает фокус в порядке Tab\n- `tabindex=\"1\"` и выше — приоритет для Tab (НЕ рекомендуется)\n\n#### Вариант 2: Фокусировать первый input\n\nЭто чаще всего то, что нужно на практике:\n\n```html\n
\n \n \n \n
\n\n\n```\n\n### Реальные примеры использования\n\n#### 1. Открыть модалку и фокусировать форму\n\n```typescript\nfunction openModal() {\n const modal = document.getElementById('modalForm');\n \n // Способ 1: Фокусировать первый input\n const firstInput = modal.querySelector('input, select, textarea');\n if (firstInput) {\n firstInput.focus();\n }\n \n // Или с tabindex\n modal.setAttribute('tabindex', '-1');\n modal.focus();\n}\n```\n\n#### 2. React компонент\n\n```typescript\nimport React, { useRef } from 'react';\n\nfunction MyForm() {\n const formRef = useRef(null);\n const firstInputRef = useRef(null);\n \n const handleOpenForm = () => {\n // Вариант 1: Фокусировать первый input\n firstInputRef.current?.focus();\n \n // Вариант 2: Сделать форму фокусируемой\n formRef.current?.setAttribute('tabindex', '-1');\n formRef.current?.focus();\n };\n \n return (\n <>\n \n
\n \n \n \n
\n \n );\n}\n```\n\n#### 3. Контроль фокуса в форме\n\n```typescript\nfunction FormWithFocusControl() {\n const formRef = useRef(null);\n const [focusedField, setFocusedField] = React.useState(null);\n \n // Фокусировать конкретный input по имени\n const focusField = (fieldName: string) => {\n const input = formRef.current?.querySelector(\n `input[name=\"${fieldName}\"]`\n ) as HTMLInputElement;\n \n if (input) {\n input.focus();\n setFocusedField(fieldName);\n }\n };\n \n return (\n
\n setFocusedField('firstName')}\n />\n setFocusedField('email')}\n />\n \n {/* Кнопка для фокусировки firstName -->\n \n \n
{focusedField && `Focused: ${focusedField}`}
\n \n );\n}\n```\n\n### Проверка фокусируемости элемента\n\n```typescript\nfunction isFocusable(element: HTMLElement): boolean {\n const focusableSelectors = [\n 'a[href]',\n 'button',\n 'input',\n 'select',\n 'textarea',\n '[tabindex]'\n ];\n \n return focusableSelectors.some(\n selector => element.matches(selector)\n );\n}\n\nconst form = document.querySelector('form');\nconsole.log(isFocusable(form)); // false\n\nconst input = form?.querySelector('input');\nconsole.log(isFocusable(input)); // true\n```\n\n### Лучшие практики\n\n1. **Не фокусируй форму** — фокусируй первый input:\n ```javascript\n const firstInput = form.querySelector('input, select, textarea');\n firstInput?.focus();\n ```\n\n2. **Управляй фокусом для доступности:**\n ```javascript\n // После отправки формы - вернуть фокус на кнопку\n submitButton.focus();\n ```\n\n3. **Используй tabindex=-1 осторожно:**\n ```html\n \n
...
\n ```\n\n4. **Тестируй фокус:**\n ```javascript\n const canFocus = () => {\n const prevActive = document.activeElement;\n element.focus();\n const isFocused = document.activeElement === element;\n prevActive?.focus?.();\n return isFocused;\n };\n ```\n\n### Заключение\n\n**Вопрос:** Будет ли работать focus на форме?\n\n**Ответ:** **Нет**, `
` по умолчанию не фокусируется. Нужно:\n\n- Либо добавить `tabindex=\"-1\"` на форму\n- Либо (чаще всего) фокусировать первый input внутри формы\n\nЭто частая ошибка в разработке, поэтому важно понимать какие элементы фокусируются, а какие нет.","dateCreated":"2026-04-02T21:51:11.026345","upvoteCount":0,"author":{"@type":"Person","name":"claude-haiku-4.5"}}}}
← Назад к вопросам

Будет ли работать focus навешанный на форму?

2.0 Middle🔥 121 комментариев
#JavaScript Core

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

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

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

Focus на элементе form: будет ли работать?

Короткий ответ: Нет, focus на <form> элементе НЕ работает так как ожидается. Это важная нюанс HTML/DOM.

Почему focus не работает на форме

<form> — это контейнерный элемент, а не интерактивный элемент. Focus в браузере может устанавливаться только на фокусируемые элементы (focusable elements):

Фокусируемые элементы:

  • <a>, <button>, <input>, <select>, <textarea>
  • <area>, <details>, <iframe>
  • Элементы с contenteditable="true"
  • Элементы с tabindex >= 0
  • И несколько других

НЕ фокусируемые по умолчанию:

  • <form>
  • <div>, <span>, <p> и другие контейнеры
  • <img>, <video> и медиа элементы
  • <ul>, <ol>, <li> и списки

Практический пример

<form id="myForm">
  <input type="text" placeholder="Name">
  <input type="email" placeholder="Email">
  <button type="submit">Submit</button>
</form>

<script>
  const form = document.getElementById('myForm');
  
  // Это НЕ будет работать
  form.focus();  // Ничего не произойдёт!
  
  // Проверим, фокусируется ли
  console.log(document.activeElement);  // <body>
  console.log(form === document.activeElement);  // false
</script>

Как сделать форму фокусируемой

Вариант 1: Добавить tabindex

<form id="myForm" tabindex="-1">
  <input type="text" placeholder="Name">
  <input type="email" placeholder="Email">
  <button type="submit">Submit</button>
</form>

<script>
  const form = document.getElementById('myForm');
  
  form.focus();  // Теперь работает!
  console.log(document.activeElement);  // <form id="myForm">
</script>

Значения tabindex:

  • tabindex="-1" — элемент фокусируется программно, но НЕ через Tab
  • tabindex="0" — элемент получает фокус в порядке Tab
  • tabindex="1" и выше — приоритет для Tab (НЕ рекомендуется)

Вариант 2: Фокусировать первый input

Это чаще всего то, что нужно на практике:

<form id="myForm">
  <input id="firstName" type="text" placeholder="Name">
  <input type="email" placeholder="Email">
  <button type="submit">Submit</button>
</form>

<script>
  const form = document.getElementById('myForm');
  const firstInput = document.getElementById('firstName');
  
  // Фокусируем первый input, а не саму форму
  firstInput.focus();  // Работает!
</script>

Реальные примеры использования

1. Открыть модалку и фокусировать форму

function openModal() {
  const modal = document.getElementById('modalForm');
  
  // Способ 1: Фокусировать первый input
  const firstInput = modal.querySelector('input, select, textarea');
  if (firstInput) {
    firstInput.focus();
  }
  
  // Или с tabindex
  modal.setAttribute('tabindex', '-1');
  modal.focus();
}

2. React компонент

import React, { useRef } from 'react';

function MyForm() {
  const formRef = useRef<HTMLFormElement>(null);
  const firstInputRef = useRef<HTMLInputElement>(null);
  
  const handleOpenForm = () => {
    // Вариант 1: Фокусировать первый input
    firstInputRef.current?.focus();
    
    // Вариант 2: Сделать форму фокусируемой
    formRef.current?.setAttribute('tabindex', '-1');
    formRef.current?.focus();
  };
  
  return (
    <>
      <button onClick={handleOpenForm}>Open Form</button>
      <form ref={formRef}>
        <input ref={firstInputRef} type="text" placeholder="Name" />
        <input type="email" placeholder="Email" />
        <button type="submit">Submit</button>
      </form>
    </>
  );
}

3. Контроль фокуса в форме

function FormWithFocusControl() {
  const formRef = useRef<HTMLFormElement>(null);
  const [focusedField, setFocusedField] = React.useState<string | null>(null);
  
  // Фокусировать конкретный input по имени
  const focusField = (fieldName: string) => {
    const input = formRef.current?.querySelector(
      `input[name="${fieldName}"]`
    ) as HTMLInputElement;
    
    if (input) {
      input.focus();
      setFocusedField(fieldName);
    }
  };
  
  return (
    <form ref={formRef}>
      <input
        name="firstName"
        type="text"
        placeholder="Name"
        onFocus={() => setFocusedField('firstName')}
      />
      <input
        name="email"
        type="email"
        placeholder="Email"
        onFocus={() => setFocusedField('email')}
      />
      
      {/* Кнопка для фокусировки firstName -->
      <button type="button" onClick={() => focusField('firstName')}>
        Focus Name
      </button>
      
      <div>{focusedField && `Focused: ${focusedField}`}</div>
    </form>
  );
}

Проверка фокусируемости элемента

function isFocusable(element: HTMLElement): boolean {
  const focusableSelectors = [
    'a[href]',
    'button',
    'input',
    'select',
    'textarea',
    '[tabindex]'
  ];
  
  return focusableSelectors.some(
    selector => element.matches(selector)
  );
}

const form = document.querySelector('form');
console.log(isFocusable(form));  // false

const input = form?.querySelector('input');
console.log(isFocusable(input));  // true

Лучшие практики

  1. Не фокусируй форму — фокусируй первый input:

    const firstInput = form.querySelector('input, select, textarea');
    firstInput?.focus();
    
  2. Управляй фокусом для доступности:

    // После отправки формы - вернуть фокус на кнопку
    submitButton.focus();
    
  3. Используй tabindex=-1 осторожно:

    <!-- Хорошо для диалогов -->
    <div role="dialog" tabindex="-1">...</div>
    
  4. Тестируй фокус:

    const canFocus = () => {
      const prevActive = document.activeElement;
      element.focus();
      const isFocused = document.activeElement === element;
      prevActive?.focus?.();
      return isFocused;
    };
    

Заключение

Вопрос: Будет ли работать focus на форме?

Ответ: Нет, <form> по умолчанию не фокусируется. Нужно:

  • Либо добавить tabindex="-1" на форму
  • Либо (чаще всего) фокусировать первый input внутри формы

Это частая ошибка в разработке, поэтому важно понимать какие элементы фокусируются, а какие нет.