javascript drop down box option click on the event to share the example

  • 2020-05-10 17:37:42
  • OfStack

I myself am engaged in front-end development of technical personnel, drop-down box is we use more page elements, today I combined with the actual work of the problems encountered in the drop-down box registration event 1 some examples, I hope to help you.


  <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 radio drop-down box code. If we want to get the corresponding value by clicking the drop-down option, the general code 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);// Gets the text value of the drop-down option
      alert(this.value);// Gets the drop-down option value value
    }
  }  

The above code does not produce the desired effect below ie9 and on chrome, and is valid on Firefox. In this case, it is not recommended to bind the click event on the option option. Instead, it is recommended to use the change event instead, because change is generic and essentially change.


  var sel=document.getElementById("sel");
  sel.onchange=function(){
    alert(sel.options[sel.selectedIndex].value);
  } 

That's all for this article, I hope you enjoy it.


Related articles: