Reputation: 17
I have a html page with select combo box.
<select id="mySelect" name="Geometrical Figures">
<option>Circle</option>
<option>Triangle</option>
<option>Square</option>
<option>Rectangle</option>
<option>Polygon</option>
</select>
<button id="imagedraw" onclick="draw()">Draw Image</button>
I have different functions to draw canvas images based on user selection
function drawcircle()
function drawrectangle()
function drawtriangle()
My query is how can I set which function to call dynamically based on user input when onclick
event is executed.
Ex: When user selects circle and clicks on Draw Image, drawCircle()
function would be called, similarly for other values.
Upvotes: 0
Views: 1591
Reputation: 364
You can know the selected item by saving the Select
element.
var mySelect = document.getElementById('MySelect');
var selected = mySelect.options[mySelect.selectedIndex].text;
Then in the draw function you can add that and then decide what to do:
function draw(){
var mySelect = document.getElementById('MySelect');
var selected = mySelect.options[mySelect.selectedIndex].text;
if(selected === 'Circle'){
drawCircle();
}
.........
}
There may be more viable solutions.
Upvotes: 1
Reputation: 175
You could create array of functions and call the function according to the selected option index.
var funcArray = [drawcircleFN,drawrectangleFN,drawtriangleFN];
var draw = function(){
var yourSelect = document.getElementById("mySelect");
var funcIndex = yourSelect.options[ yourSelect.selectedIndex ].value;
funcArray[funcIndex]();
}
Upvotes: 0
Reputation: 2190
Maybe assign a value
to each option
and use a switch
to decide which function to call?
You could also use the function name as value
of the option
and call the function by string:
<option value="drawCircle">Circle</option>
function draw() {
window[document.getElementById("mySelect").value]();
}
Upvotes: 0