I require the selected option’s font/background colors change permanently to for example red/yellow after user completed the selection.
Constraints:
- Code must work in IE11.
- No jquery. Pure js.
- Form has id. Selects, options do not have id.
- Form has tens of selects.
- Solution does not have to be inline js.
- If it is a must for solution, I can add class to selects and/or options.
As an example assume “health” was selected from below. So “health” should be seen red/yellow after selection completed and clicked to a space in the page
I don’t know js. I tried as below and did not work in ie11. Browser js is enabled. I couldn’t find an existing Q/A proper for me.
JavaScript
x
7
1
<form id="myform" name="myform" method="post" accept-charset="utf-8">
2
<select name="select1" onchange="this.options[this.selectedIndex].style.color='red'">
3
<option value="0">Select</option>
4
<option style="color:#333;" value="1">Health</option>
5
<option value="2">Wisdom</option>
6
</form>
7
- why my trial did not work?
- how to make it work while satisfying my constraints?
here is the jsbin link: https://jsbin.com/hubigarofa/1/edit?html,output
thanks, regards
Advertisement
Answer
Make a seperate function and on call pass the element to that function using this
JavaScript
1
12
12
1
function a(elem)
2
{
3
document.querySelector('select').style.backgroundColor = ""
4
document.querySelector('select').style.color = ""
5
elem.options[elem.selectedIndex].style.color='red'
6
if(elem.value=="1")
7
{
8
9
document.querySelector('select').style.backgroundColor = "yellow"
10
document.querySelector('select').style.color = "red"
11
}
12
}
JavaScript
1
6
1
<form id="myform" name="myform" method="post" accept-charset="utf-8">
2
<select name="select1" onchange="a(this)">
3
<option value="0">Select</option>
4
<option style="color:yellow;" value="1">Health</option>
5
<option value="2">Wisdom</option>
6
</form>