Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
184
rated 0 times [  188] [ 4]  / answers: 1 / hits: 18637  / 10 Years ago, sat, march 15, 2014, 12:00:00

I'm searching a while for a Javascript function that changes the background-color of my select field if an option is selected.



HTML:



<select name=classNumber id=classNumber>
<option selected disabled value=0>Bitte Klasse auswählen</option>
<option value=5>5</option>
<option value=6>6</option>
<option value=7>7</option>
<option value=8>8</option>
<option value=9>9</option>
<option value=10>10</option>
<option value=11>11</option>
<option value=12>12</option>
<option value=13>13</option>
</select>
<select name=classSpecify id=classSpecify>
<option selected disabled value=0>Bitte Klasse spezifizieren</option>
<option value=A>A</option>
<option value=B>B</option>
<option value=D>C</option>
<option value=D>D</option>
<option value=N>N (Naturwissenschaftliches Profil)</option>
<option value=S>S (Sprachliches Profil)</option>
<option value=G>G (Gesellschaftliches Profil)</option>
</select>


Javascript that is not working, at this time just for testing I set up just one select:



var classNumber = document.getElementById('classNumber');
var first = classNumber.options[classNumber.selectedIndex].value;
if (first != 0) {
alert('Test');
document.getElementById('classNumber').style.background=$green;
};

More From » html

 Answers
130

I'm assuming you want to stay away from jQuery.



You are missing a few things. First off there is nothing that calling your if statement when a user CHANGES the select. Add an event .onchange to classNumber as well as background to backgroundcolor.



Like so.



var classNumber = document.getElementById('classNumber');
classNumber.onchange = runBackgroundChange;

function runBackgroundChange(first){
var value = first.srcElement.options[first.srcElement.selectedIndex].value;
if (value != 0) {
alert('Test');
document.getElementById('classNumber').style.backgroundColor=green;
} else {
document.getElementById('classNumber').style.backgroundColor=initial;
};
}

[#71978] Thursday, March 13, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gavenmekhio

Total Points: 732
Total Questions: 89
Total Answers: 93

Location: Central African Republic
Member since Mon, Aug 10, 2020
4 Years ago
;