I am having an issue with a drop-down list that offers two options: blue and green. When I select blue and click on the text input field, its background color alternates between blue and black (the default text field color). The same applies when I choose the red option. However, the code I have only functions correctly for the first and second selections. Starting from the third selection, even if I choose red, it toggles between blue and another color. Here is my HTML:
Can anyone identify what is going wrong? I suspect that my understanding of how jQuery's change function operates may be incomplete.
$('#change_color').on('change', function() {
// Get the selected option's text value
var colorOption = $("#change_color option:selected").text();
// If 'Red' is chosen, change input box to red
if (colorOption === 'Red') {
$('.my-input').click(function(inputBox) {
$(inputBox.target).toggleClass('red');
});
}
// If 'Blue' is chosen, change input box to blue
else {
$('.my-input').click(function(inputBox) {
$(inputBox.target).toggleClass('blue');
});
}
});
.my-input {
background-color: black;
width: 5%;
font-size: 3vw;
}
.red {
background-color: red;
width: 5%;
font-size: 3vw;
}
.blue {
background-color: blue;
width: 5%;
font-size: 3vw;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="change_color" class="form-control box-border" placeholder="SPECIAL CHAR">
<option selected disabled>Special Char</option>
<option>Red</option>
<option>Blue</option>
</select>
<input type="text" class="my-input">
<input type="text" class="my-input">
<input type="text" class="my-input">