Метод setAttribute() используется для программного
добавления HTML-атрибутов элементу. В контексте библиотеки AutoNumeric
этот подход особенно полезен при динамическом создании полей ввода,
генерации интерфейсов через Javascript, работе с шаблонами и интеграции
с серверными фреймворками.
AutoNumeric поддерживает чтение конфигурации непосредственно из HTML-атрибутов элемента. Это позволяет задавать параметры форматирования без передачи большого объекта настроек в конструктор.
Метод setAttribute() добавляет или изменяет
HTML-атрибут:
element.setAttribute(name, value);
Пример:
const input = document.querySelector('#price');
input.setAttribute('value', '1000');
input.setAttribute('placeholder', 'Введите сумму');
При использовании с AutoNumeric через атрибуты обычно задаются параметры форматирования:
input.setAttribute('data-digit-group-separator', ' ');
input.setAttribute('data-decimal-character', ',');
input.setAttribute('data-currency-symbol', '₸');
После этого инициализируется AutoNumeric:
new AutoNumeric(input);
Библиотека автоматически считывает атрибуты data-* и
применяет соответствующие настройки.
data-*HTML5 ввёл специальный механизм пользовательских атрибутов:
data-*
Такие атрибуты:
AutoNumeric использует именно этот механизм.
Пример:
<input
id="amount"
data-decimal-character=","
data-digit-group-separator=" "
>
Чаще всего атрибуты устанавливаются до создания экземпляра AutoNumeric.
const input = document.querySelector('#salary');
input.setAttribute('data-currency-symbol', '$');
input.setAttribute('data-decimal-character', '.');
input.setAttribute('data-digit-group-separator', ',');
new AutoNumeric(input);
Результат:
1,234,567.89 $
Одно из самых распространённых применений — создание input-элемента полностью через Javascript.
const input = document.createElement('input');
input.type = 'text';
input.setAttribute('data-currency-symbol', '€');
input.setAttribute('data-decimal-character', ',');
input.setAttribute('data-digit-group-separator', '.');
document.body.appendChild(input);
new AutoNumeric(input);
Такой подход используется:
Через setAttribute() можно задавать ограничения.
input.setAttribute('data-minimum-value', '0');
input.setAttribute('data-maximum-value', '100000');
Инициализация:
new AutoNumeric(input);
Теперь поле не позволит выйти за указанный диапазон.
input.setAttribute('data-decimal-places', '2');
Результат:
1234,50
const input = document.querySelector('#percent');
input.setAttribute('data-decimal-character', ',');
input.setAttribute('data-decimal-places', '4');
new AutoNumeric(input);
Формат:
15,1234
input.setAttribute('data-currency-symbol', ' ₽');
input.setAttribute('data-currency-symbol', '$');
input.setAttribute('data-currency-symbol-placement', 'p');
Результат:
$1,500.00
input.setAttribute('data-currency-symbol-placement', 's');
Результат:
1 500,00 ₽
input.setAttribute('data-decimal-character', ',');
input.setAttribute('data-digit-group-separator', '.');
Результат:
1.234.567,89
input.setAttribute('data-decimal-character', '.');
input.setAttribute('data-digit-group-separator', ',');
Результат:
1,234,567.89
Иногда требуется полностью убрать разделение тысяч.
input.setAttribute('data-digit-group-separator', '');
Результат:
1000000.25
datasetsetAttribute() и dataset решают схожие
задачи.
setAttributeinput.setAttribute('data-decimal-character', ',');
datasetinput.dataset.decimalCharacter = ',';
Оба варианта работают, но между ними есть различия.
setAttribute() и datasetsetAttribute()Работает напрямую с HTML-атрибутами.
Плюсы:
Минусы:
datasetРаботает только с data-*.
Плюсы:
Минусы:
data-*;const input = document.querySelector('#invoice');
input.setAttribute('data-currency-symbol', '₸');
input.setAttribute('data-currency-symbol-placement', 's');
input.setAttribute('data-decimal-character', ',');
input.setAttribute('data-digit-group-separator', ' ');
input.setAttribute('data-decimal-places', '2');
input.setAttribute('data-minimum-value', '0');
input.setAttribute('data-maximum-value', '100000000');
new AutoNumeric(input);
Результат форматирования:
12 500 000,00 ₸
Важная особенность AutoNumeric: изменение data-* после
создания экземпляра не всегда автоматически обновляет поведение
поля.
const an = new AutoNumeric(input);
input.setAttribute('data-decimal-character', ',');
Форматирование может не измениться.
Причина:
Для изменения конфигурации после создания экземпляра рекомендуется использовать методы самой библиотеки.
update()an.update({
decimalCharacter: ','
});
Этот способ предпочтительнее, чем изменение data-* через
DOM.
setAttribute() особенно полезенrows.forEach(row => {
const input = document.createElement('input');
input.setAttribute('data-currency-symbol', '$');
input.setAttribute('data-decimal-places', '2');
new AutoNumeric(input);
});
template.content
.querySelector('input')
.setAttribute('data-digit-group-separator', ' ');
Backend может формировать:
<input
data-currency-symbol="₽"
data-decimal-character=","
data-decimal-places="2"
>
Frontend затем просто запускает:
new AutoNumeric.multiple('input');
В React прямое использование setAttribute() встречается
реже, но возможно через ref.
import { useEffect, useRef } from 'react';
function PriceInput() {
const inputRef = useRef(null);
useEffect(() => {
const input = inputRef.current;
input.setAttribute('data-currency-symbol', '$');
input.setAttribute('data-decimal-places', '2');
new AutoNumeric(input);
}, []);
return <input ref={inputRef} />;
}
mounted() {
this.$refs.price.setAttribute(
'data-currency-symbol',
'€'
);
new AutoNumeric(this.$refs.price);
}
Иногда интерфейс динамически добавляет поля в DOM. В таких случаях можно автоматически отслеживать появление новых элементов.
const observer = new MutationObserver(() => {
document.querySelectorAll('.money').forEach(input => {
if (!input.dataset.initialized) {
input.setAttribute(
'data-currency-symbol',
'$'
);
new AutoNumeric(input);
input.dataset.initialized = 'true';
}
});
});
observer.observe(document.body, {
childList: true,
subtree: true
});
Неправильно:
const an = new AutoNumeric(input);
input.setAttribute('data-decimal-character', ',');
Правильно:
input.setAttribute('data-decimal-character', ',');
const an = new AutoNumeric(input);
Неправильно:
input.setAttribute('decimal-character', ',');
Правильно:
input.setAttribute('data-decimal-character', ',');
HTML-атрибуты всегда строковые.
Лучше:
input.setAttribute('data-decimal-places', '2');
А не:
input.setAttribute('data-decimal-places', 2);
setAttribute() — относительно недорогая операция, однако
при массовом создании элементов желательно:
const input = document.createElement('input');
input.setAttribute('data-currency-symbol', '$');
input.setAttribute('data-decimal-places', '2');
container.appendChild(input);
new AutoNumeric(input);
setAttribute() может одновременно настраивать и
AutoNumeric, и обычное поведение input.
input.setAttribute('type', 'text');
input.setAttribute('placeholder', 'Введите сумму');
input.setAttribute('autocomplete', 'off');
input.setAttribute('data-currency-symbol', '₽');
input.setAttribute('data-decimal-places', '2');
function createMoneyInput(options) {
const input = document.createElement('input');
input.setAttribute(
'data-currency-symbol',
options.symbol
);
input.setAttribute(
'data-decimal-character',
options.decimal
);
input.setAttribute(
'data-digit-group-separator',
options.separator
);
input.setAttribute(
'data-decimal-places',
options.precision
);
new AutoNumeric(input);
return input;
}
const field = createMoneyInput({
symbol: '$',
decimal: '.',
separator: ',',
precision: '2'
});
document.body.appendChild(field);
Такой подход часто используется в: