When choosing the country code, the picture is undefined, the problem is most likely in js, but I’m not sure, please help.
let header = document.querySelectorAll('.select__header')
let item = document.querySelectorAll('.select__item')
let select = document.querySelector('.select')
let images = document.querySelectorAll('.select__item img')
header.forEach(i => {
i.addEventListener('click', () => {
i.parentElement.classList.toggle('active')
})
})
item.forEach(i => {
i.addEventListener('click', () => {
images.forEach(el => {
let text = images[el] + i.textContent,
currentText = select.querySelector('.select__current')
currentText.innerText = text
select.classList.remove('active')
console.log(images);
})
})
})
.select {
width: 110px;
position: relative;
}
.select img {
width: 30px;
}
.select__header {
border: 1px solid #ccc;
cursor: pointer;
display: flex;
}
.select__current {
font-size: 18px;
padding: 8px;
}
.select__icon {
display: flex;
justify-content: center;
align-items: center;
flex-shrink: 0;
height: 40px;
width: 15px;
margin-left: auto;
}
.select__icon img {
width: 10px;
}
.select__body {
display: none;
left: 0;
right: 0;
border: 1px solid #ccc;
position: absolute;
top: 100%;
background-color: #fff;
}
.select__item {
line-height: 24px;
padding: 8px;
font-size: 16px;
cursor: pointer;
}
.select__item:hover {
background-color: #ccc;
}
.select.active .select__body {
display: block;
}
<div class="select">
<div class="select__header">
<span class="select__current"> <img src="./img/rus.jpg" alt=""> +7</span>
<span class="select__icon"><img src="./img/Stroke.svg" alt=""></span>
</div>
<div class="select__body">
<div class="select__item"><img src="./img/rus.jpg" alt="">+7</div>
<div class="select__item"><img src="./img/usa.jpg" alt="">+1</div>
<div class="select__item"><img src="./img/Flag_of_Turkey.svg.webp" alt="">+90</div>
</div>
</div>
I think problem there:
let text = images[el] + i.textContent
I would like an image with the country code to be displayed when selecting a country. But unfortunately it didn’t quite work out.
3
Answers
item and images are two different arrays which you nested images inside items with no clear meaning. There is no need to prepare an array of all images. Just for each item you can find the image using this code:
Delegate and simplify
})