Селектор :optional у CSS — поля без атрибута required
Селектор :optional застосовується для вибірки не обов'язкових до заповнення полів.
Цей селектор застосовується тільки до елемнтів форми, таких як input, select чи textarea.
Загальний опис
автор: NagarD
- Порада
-
Використовуйте селектор
автор: NagarD:requiredдля вибірки елементів форми, що обов'язкові до заповнення.
Синтаксис
:optional {
css declarations;
}
Переглядачі
| Переглядач | ||||||
|---|---|---|---|---|---|---|
| 10 | 4 | 5 | 10 | 12 | 10 |
| Переглядач | ||||
|---|---|---|---|---|
| 37 | 18 | 4 | 5 |
Приклади
+ запропонувати свій приклад у пісочниці
Жовтим стає лише поле без атрибута required — тобто необов'язкове.
HTML
<input type="text" placeholder="необов'язкове — жовте">
<input type="text" required placeholder="обов'язкове (required)">
CSS
input:optional {
background-color: yellow;
}
Зелена рамка — :optional, червона — :required. Половина контролів не дістала жодної: для submit, range, color і hidden обов'язковості не існує. Таблиця під формою перелічує, що саме взяв кожен псевдоклас.
HTML
<form class="card">
<p><label>текст без required <input type="text" value="взято :optional"></label></p>
<p><label>текст із required <input type="text" required value="взято :required"></label></p>
<p><label>вимкнене поле <input type="text" disabled value="усе одно :optional"></label></p>
<p><label>лише для читання <input type="text" readonly value="усе одно :optional"></label></p>
<p><label>прапорець <input type="checkbox"></label>
<label>перемикач <input type="radio" name="r"></label></p>
<p><label>повзунок <input type="range"></label>
<label>колір <input type="color"></label></p>
<p><label>список <select><option>раз</option></select></label></p>
<p><label>область тексту <textarea rows="2"></textarea></label></p>
<p><button type="submit">кнопка — не поле</button>
<input type="submit" value="теж не поле">
<output>і це не поле</output></p>
<input type="hidden" value="прихованого не видно, і він теж повз">
</form>
<table id="report">
<thead><tr><th>псевдоклас</th><th>з чим збігся</th></tr></thead>
<tbody></tbody>
</table>
CSS
.card {
max-width: 560px;
padding: 4px 14px 12px;
border: 1px solid #b9c6d8;
border-radius: 6px;
background: #f6f9ff;
}
.card p {
margin: 12px 0;
}
.card label {
margin-right: 14px;
}
:optional {
outline: 3px solid #3a9a4f;
outline-offset: 2px;
}
:required {
outline: 3px solid #d64545;
outline-offset: 2px;
}
select,
textarea,
input[type="text"] {
padding: 4px 6px;
border: 1px solid #b9c6d8;
border-radius: 4px;
font: inherit;
}
table {
margin-top: 14px;
border-collapse: collapse;
font-size: .88rem;
}
th,
td {
padding: 5px 9px;
border: 1px solid #b9c6d8;
text-align: left;
vertical-align: top;
}
th {
background: #eef4ff;
}
code {
background: #eef4ff;
border-radius: 3px;
padding: 0 4px;
}
JS
const opysaty = (el) => el.tagName.toLowerCase() + (el.type ? '[' + el.type + ']' : '');
const OPTIONAL = [...document.querySelectorAll(':optional')].map(opysaty);
const REQUIRED = [...document.querySelectorAll(':required')].map(opysaty);
const VSI = [...document.querySelectorAll('input, select, textarea, button, output')].map(opysaty);
const POZA = VSI.filter((n) => !OPTIONAL.includes(n) && !REQUIRED.includes(n));
const tbody = document.querySelector('#report tbody');
for (const [nazva, spysok] of [[':optional', OPTIONAL], [':required', REQUIRED], ['ні те, ні те', POZA]]) {
const row = tbody.insertRow();
row.insertCell().textContent = nazva;
row.insertCell().textContent = spysok.join(', ');
}
console.log(':optional взяв', OPTIONAL.length, 'елементів:', OPTIONAL.join(', '));
// → input[text], input[text], input[text], input[checkbox], input[radio], select[select-one], textarea[textarea]
console.log(':required взяв:', REQUIRED.join(', ')); // → input[text]
console.log('поза обома псевдокласами:', POZA.join(', '));
// → input[range], input[color], button[submit], input[submit], output[output], input[hidden]
// вимкнене й лише для читання поля все одно необов'язкові
const vymknene = document.querySelector('input[disabled]');
const chytannya = document.querySelector('input[readonly]');
console.log('disabled — :optional?', vymknene.matches(':optional')); // → true
console.log('readonly — :optional?', chytannya.matches(':optional')); // → true
// а поле поза формою обов'язковим бути нема перед ким
const samotnje = document.createElement('input');
document.body.append(samotnje);
console.log('поле поза формою — :optional?', samotnje.matches(':optional')); // → true
samotnje.remove();
// ⚠️ :optional і :not(:required) — різні речі за обсягом
console.log(':optional по документу:', document.querySelectorAll(':optional').length,
'| :not(:required):', document.querySelectorAll(':not(:required)').length,
'— друге бере ще й абзаци, таблиці та саму html'); // → 7 проти 58
Коментарі
Коментарів ще немає — будьте першим!