I am a technician engaged in front-end development. The drop-down box is the page element we use more. Today, I will talk about some examples of the drop-down box registration event based on the problems encountered in actual work. I hope it will be helpful to everyone.
The code copy is as follows:
<select name="" id="sel">
<option value="111">1</option>
<option value="222">2</option>
<option value="333">3</option>
</select>
The above is a very simple single-choice drop-down box code. If we want to get the corresponding value by clicking the drop-down option, the general code is as follows:
The code copy is as follows:
var sel=document.getElementById("sel");
var option=sel.options;
for(var i=0;i<option.length;i++){
option[i].onclick=function(){
alert(this.text);//Get the text value of the drop-down option
alert(this.value);//Get the value of the drop-down option
}
}
The above code cannot produce the expected effect below ie9 and chrome, and is effective on Firefox. In this case, it is not recommended to bind click events on the option option. It is recommended to use change events instead, because change is general and essentially it is change.
The code copy is as follows:
var sel=document.getElementById("sel");
sel.onchange=function(){
alert(sel.options[sel.selectedIndex].value);
}
The above is all about this article, I hope you like it.