Search code examples
javascriptlistselectonchangetritium

Convert ul with onclick() into select with onchange()


I have a ul containing a series of tabs with onclick() attributes, and I want to convert it into a select node with options instead of list items. Right now each tab has its own onclick() attribute, but it looks like a select node only has one onchange() attribute. How do I tell the select to run the js indicated by the selected option on change?


Solution

  • When the onchange event runs get the .value like you would for any time of form element and then run whatever javascript is appropriate.

    document.getElementById('selectElement').onchange=function(e){
      var ele = event.target || event.srcElement;//This would be the select element
      var val=ele.value;
      if(val=='option1'){
        callFunction1();
      }
      else if(val=='option2'){
        callFunction2();
      }
      //Alternatively you could set up an object for all your functions and call it like this
      var actions={
        option1:function(){},
        option2:function(){}
      }
      actions[val]()
    }