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

<select> with <option> to load js functions. Vanilla js preferred. JavaScript

  • SOLVED

I want <select> with <option> to load js functions. Vanilla js preferred.

<select name="forma" onchange="(this.value;)">
<option>SNAPSHOT</option>
<option value="progressive();">display snapshot of pairings</option>
<option value="geico();">create snapshot of pairings</option>
</select>

Answers (2)

2019-04-02

Rainner Lins answers:

Something like this if your JS code is defined before the HTML:

https://jsfiddle.net/co8fk2Lu/


<script>
function func1() {
alert( 'function 1' );
}
function func2() {
alert( 'function 2' );
}

function onSelect( val ) {
switch( val ) {
case 'opt1': return func1();
case 'opt2': return func2();
}
}
</script>

<select onchange="onSelect( this.value )">
<option value="">Select option</option>
<option value="opt1">Option 1</option>
<option value="opt2">Option 2</option>
</select>


Or, something like this if your JS code is loaded at the bottom or when the page is ready:

https://jsfiddle.net/n2xam17y/


<select id="mySelect">
<option value="">Select option</option>
<option value="opt1">Option 1</option>
<option value="opt2">Option 2</option>
</select>

function func1() {
alert( 'function 1' );
}
function func2() {
alert( 'function 2' );
}

// find the select menu by id and listen for the change event on it
document.querySelector( '#mySelect' ).addEventListener( 'change', e => {
switch( e.target.value ) {
case 'opt1': return func1();
case 'opt2': return func2();
}
});


User180435 comments:

No. This is not what I requested. I don't need a browser alert. I need to place the name of the javascript function in the <option value = "myFunction();"> and select it and have that function run. Can you please help? I think you are an outstanding programmer.


Rainner Lins comments:

Those are example functions. Rename them to be whatever you want them to be from your code.


Rainner Lins comments:

The switch() part is what reads the selected value from the select menu and decides what function to call. You would want to change that to call your own functions.

You can read more on the switch statement here:

https://javascript.info/switch

2019-04-03

Arnav Joy answers:

can you please describe what these function will do?
or why you want to call function directly within option of select?