Warrior Forum - The #1 Digital Marketing Forum & Marketplace

Warrior Forum - The #1 Digital Marketing Forum & Marketplace (https://www.warriorforum.com/)
-   Programming (https://www.warriorforum.com/programming/)
-   -   Execute a function when selected - javascript (https://www.warriorforum.com/programming/637108-execute-function-when-selected-javascript.html)

kojakeugenio 16th July 2012 04:06 AM

Execute a function when selected - javascript
 
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

kdavies 16th July 2012 04:19 AM

Re: Execute a function when selected - javascript
 
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();

kojakeugenio 16th July 2012 05:03 AM

Re: Execute a function when selected - javascript
 
Hi kdavies thanks! How can I execute that function if any value on the list is selected?

Brandon Tanner 16th July 2012 09:06 AM

Re: Execute a function when selected - javascript
 
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>


John Ayling 16th July 2012 09:18 AM

Re: Execute a function when selected - javascript
 
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>



All times are GMT -6. The time now is 06:48 AM.