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.
<form id="myform" name="myform" method="post" accept-charset="utf-8"> <select name="select1" onchange="this.options[this.selectedIndex].style.color='red'"> <option value="0">Select</option> <option style="color:#333;" value="1">Health</option> <option value="2">Wisdom</option> </form>
- 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
function a(elem) { document.querySelector('select').style.backgroundColor = "" document.querySelector('select').style.color = "" elem.options[elem.selectedIndex].style.color='red' if(elem.value=="1") { document.querySelector('select').style.backgroundColor = "yellow" document.querySelector('select').style.color = "red" } }
<form id="myform" name="myform" method="post" accept-charset="utf-8"> <select name="select1" onchange="a(this)"> <option value="0">Select</option> <option style="color:yellow;" value="1">Health</option> <option value="2">Wisdom</option> </form>