Ask your JavaScript questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

<select> with <option> to execute a javascript function. JavaScript

  • REFUNDED

I want to use a <select> with <option> to execute a javascript function. Use JS or JQUERY

<select id = "myID" onchange="{functionName()}">

<option value="myFunction_1()">Function A</option>
<option value="myFunction_2()">Function B</option>
<option value="myFunction_3()">Function C</option>

</select>

Answers (2)

2019-01-08

Arnav Joy answers:

So you want to do something on change of select box?


Arnav Joy comments:

You can use this


$('select').on('change', function() {
alert( this.value );
});


User180435 comments:

Yes. I want to execute the <option value = "whatever_function();" >


Arnav Joy comments:

You can try this


$('select').on('change', function() {
If( this.value == option1 )
Myfunction1();

If( this.value == option2 )
Myfunction2();

If( this.value == option3 )
Myfunction3();
});


User180435 comments:

I want to execute the function... <option value="loadUSCF();">our uscf database</option>

Not just place it in an alert.


User180435 comments:

<script>
$('select').on('change', function() {
if ( this.value == "our uscf database" )
{loadUSCF();}
});

</script>


<select>
<option selected value="">Make a Selection</option>
<option value="loadUSCF();">our uscf database</option>
</select>

This doesn't work.

2019-01-08

Rainner Lins answers:

Think of the select input as a text input where the value changes and you do something with it. Each option is a pre-defined value you can choose from.


<select id="mySelectBox">
<option value="">Select one</option>
<option value="loadUSCF">Function A</option>
<option value="otherStuff">Function B</option>
<option value="moreStuff">Function C</option>
</select>




let select = document.querySelector( '#mySelectBox' );

// listen for when the value changes
select.addEventListener( 'change', e => {

// this is the value that was selected
let val = e.target.value;

if ( val === 'loadUSCF' ) {
// call your function
// loadUSCF();
}

if ( val === 'otherStuff' ) {
// do something
}

if ( val === 'otherStuff' ) {
// do something
}

console.log( val );
});


Here's a working example:
https://jsfiddle.net/b64k390s/