Execute a function when selected - javascript

4 replies
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
#execute #function #javascript #selected
  • Profile picture of the author kdavies
    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();
    {{ DiscussionBoard.errors[6616402].message }}
  • Profile picture of the author kojakeugenio
    Hi kdavies thanks! How can I execute that function if any value on the list is selected?
    Signature
    Best Blog Commenting Software
    Youlikehits ROBOT - Earn 15k+ points daily for FREE!
    Contact me for your Custom Bot Needs - CLICK HERE!
    {{ DiscussionBoard.errors[6616544].message }}
  • Profile picture of the author Brandon Tanner
    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>
    Signature

    {{ DiscussionBoard.errors[6617715].message }}
  • Profile picture of the author John Ayling
    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>
    Signature
    Software Marketing & Licensing System for WordPress Plugins, Themes & .NET Software
    >> 72 Hour Special <<
    {{ DiscussionBoard.errors[6617778].message }}

Trending Topics