Reputation: 23
I want to change bg color of select when user choose option red then background of select all red. When user select pink then select background color is pink. Trying to solve this problem for about 3 hours.
I tried already addEventListener, also onchange in select but not working.
const select = document.querySelector('#select');
select.addEventListener('change', (event) => {
console.log(event.target.value)
if (event.target.value = 'red') {
select.style.background = 'red';
}
else if (event.target.value = 'pink') {
select.style.background = 'pink'
}
else {
select.style.background = 'yellow'
}
});
<select id="select">
<option value="red">red</option>
<option value="pink">pink</option>
<option value="yellow">yellow</option>
</select>
In console I can see that event.target.value = red, pink, yellow. Color of select is changing only once for red, and if u select another option - nothing happen. No errors in editor or console. Hope someone can help me, thanks a lot.
Upvotes: 1
Views: 695
Reputation: 187
You are using querySelector
incorrectly. It should be called as a method with the selector as it's argument, like so:
const select = document.querySelector('#select');
Upvotes: 0
Reputation: 11574
Firstly, you define select
incorrectly. Secondly your if
predicates should use the equality comparator ===
, rather than the assignment operator =
.
const select = document.querySelector('#select');
select.addEventListener('change', (event) => {
console.log(event.target.value)
if (event.target.value === 'red') {
select.style.background = 'red';
} else if (event.target.value === 'pink') {
select.style.background = 'pink'
} else {
select.style.background = 'yellow'
}
});
<select id="select">
<option value="red">red</option>
<option value="pink">pink</option>
<option value="yellow">yellow</option>
</select>
Upvotes: 0
Reputation: 7665
document.querySelector
is a method, so that you should call it as a function:
document.querySelector('#select')
Also, you can directly write select value as a background color, in this way you don't need if/else conditions:
select.style.background = event.target.value
The final version may look like as follows:
const select = document.querySelector('#select');
select.addEventListener('change', (event) => {
select.style.background = event.target.value
});
<select id="select">
<option value="red">red</option>
<option value="pink">pink</option>
<option value="yellow">yellow</option>
</select>
Upvotes: 1