Answer the question
In order to leave comments, you need to log in
How to optimize the text change code after clicking on the button?
Good afternoon. It is necessary to implement a mechanism on the site: by clicking on the + and - buttons, the price is added and subtracted. Moreover, the price step can be uneven.
I've written a script to the best of my experience, it works exactly as I need it, but I find it very cumbersome and unoptimized. Please tell me how to make it more beautiful, I will be grateful not even for the finished code, but just for the train of thought :)
My code:
function plusPrice() {
plus.addEventListener('click', (e) => {
e.preventDefault();
person.value++;
if (person.value >= 10) {
person.value = 10;
}
if (person.value == 2) {
price.textContent = `245 000 ₸`;
}
if (person.value == 3) {
price.textContent = `240 000 ₸`;
}
if (person.value == 4) {
price.textContent = `238 000 ₸`;
}
if (person.value == 5) {
price.textContent = `235 000 ₸`;
}
if (person.value == 6) {
price.textContent = `230 000 ₸`;
}
if (person.value == 7) {
price.textContent = `225 000 ₸`;
}
if (person.value == 8) {
price.textContent = `220 000 ₸`;
}
if (person.value == 9) {
price.textContent = `215 000 ₸`;
}
});
}
plusPrice();
Answer the question
In order to leave comments, you need to log in
let quantity = 1; // изначально 1
// цены в тыс. для числа-индекса (считается от 0: 0, 1, 2, ... 9)
const prices = [0, 250, 245, 240, 238, 235, 230, 225, 220, 215]; // 1..9
// клик на плюс
plus.addEventListener('click', (e) => {
e.preventDefault();
fixPrice(+1);
});
// клик на минус
minus.addEventListener('click', (e) => {
e.preventDefault();
fixPrice(-1);
});
// пересчет цены
const fixPrice = (delta) => {
// обновить количество
quantity += delta; // +/- 1
quantity = Math.max(1, quantity); // не меньше 1
quantity = Math.min(9, quantity); // не больше 9
// показать новые значения
person.value = quantity; // показать новое число персон
price.textContent = `${prices[quantity]} 000 ₸`; // показать цену
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question