Execute a function when selected - javascript

by 4 replies
5
How can achieve this. For example on this code:

Code:
<select name="">
  <option value="test1">test1</option>
  <option value="test2">test2</option>
  <option value="test3">test3</option>
</select>
When I select test2 it will trigger a function?

Please advise..

Thanks
#programming #execute #function #javascript #selected
  • Give the select object and id and in your javascript add something like:

    var dothis = function(){
    return function(e){
    var s = document.getElementById('yourId');
    if(s.options[s.selectedIndex]=='test2'){
    // YOUR CODE HERE
    }
    }
    }
    document.getElementById('yourId').onchange = dothis();
  • Hi kdavies thanks! How can I execute that function if any value on the list is selected?
  • Here's another way to do it...

    Code:
    <!-- Javascript -->
    
    <script type="text/javascript">
         function test1() {
         alert("You chose 1!");
         }
         function test2() {
         alert("You chose 2!");
         }
         function test3() {
         alert("You chose 3!");
         }  
    </script>
    
    
    <!-- HTML -->
    
    <select name="">
      <option value="test1" onclick="test1()">test1</option>
      <option value="test2" onclick="test2()">test2</option>
      <option value="test3" onclick="test3()">test3</option>
    </select>
  • And if you want to use jQuery..

    Code:
    <script type="text/javascript">
    $(document).ready(function(){
         $('#mySelect').change(function(){
               var selectedOption = $(this).val();
               alert("You selected " + selectedOption);
          });
    });
    </script>
    
    
    <select name="" id="mySelect"> 
         <option value="test1">test1</option> 
         <option value="test2">test2</option> 
         <option value="test3">test3</option> 
    </select>

Next Topics on Trending Feed