const prices = document.querySelectorAll('.price');
prices.forEach(price => {
price.addEventListener('click', e => {
prices.forEach(el => el.classList.remove('active'));
e.target.classList.add('active');
const currentValue = e.target.value;
})
})
<ul class="money">
<li class="price" data-value="20">20 ฿</li>
<li class="price" data-value="50">50 ฿</li>
<li class="price" data-value="100">100 ฿</li>
<li class="price" data-value="250">250 ฿</li>
<ul>
My problem:
- When i change value, value is store multiple in currentValue
variable. - (I want to get 1 value)
- please explain to me and post website for more understand.
3
Answers
The attribute
data-value
can be found asprice.dataset.value
in your script:The
e.target.value
is used to get input element’s value.To get an element’s text value, you need to use
element.textContent
.If you want to get the value from data attribute, you can use
element.dataset.value
.You can also use the element.getAttribute() method to get your value. Also, just as an aside, you can use event delegation to simplify your javascript plus you only need one event listener on the parent rather than one on each
li
as follows: