<h2>Шоп</h2>
<p>Добавьте товаров в авоську</p>
<div class="selectors"></div>
<div class="my-4">
<button id="calculate">Рассчитать</button>
</div>
<div id="total"></div>
.hidden {
display: none;
}
.selectors > select, .selectors > button {
margin:0 10px;
}
.my-4 {
padding: 20px 0 20px;
margin: 20px 0 20px;
border-top: 1px solid #777;
border-bottom: 1px solid #ccc;
}
const options = [
[null, 'Выберите'],
['domain', 'домен'],
['hosting', 'хостинг'],
];
const createSelect = () => {
const select = document.createElement('select');
select.name = 'products[]';
options.forEach(([value, title]) => {
const option = document.createElement('option');
option.innerText = title;
if (value) {
option.value = value;
} else {
option.setAttribute('disabled', true);
option.setAttribute('selected', true);
}
select.appendChild(option);
});
return select;
};
// в стили добавить ".hidden { display: none; }"
const HIDDEN_CLASS = 'hidden';
const createButton = () => {
const button = document.createElement('button');
button.type = 'button';
button.textContent = 'Выбрать ещё один';
button.classList.add(HIDDEN_CLASS);
return button;
};
// Элемент, куда будут добавляться селекты с кнопками
const parent = document.querySelector('div.selectors');
const addItem = (callback) => {
const handler = () => {
if (callback) callback();
const select = createSelect();
const button = createButton();
const revealButton = () => {
button.classList.remove('hidden');
select.removeEventListener('input', revealButton); // once!
};
const hideAgainButton = () => {
button.classList.add(HIDDEN_CLASS);
button.setAttribute('disabled', true);
};
select.addEventListener('input', revealButton);
button.addEventListener('click', addItem(hideAgainButton));
parent.appendChild(select);
parent.appendChild(button);
};
if (!callback) return handler();
return handler;
};
addItem(); // первый пошёл
const calculate = () => {
document.getElementById('total').innerText = Array.from(document.querySelectorAll('select[name="products[]"]')).map(el => el.value).join(' + ');
};
document.getElementById('calculate').addEventListener('click', calculate);
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.