'Reflect select state in JavaScript function
In JavaScript how do you make it so that a function is ready to change at any moment? I want to make it so that when someone selects a different option from a drop down form an image for that selected type will appear. Such as something like this:
newTexture(document.worktopForm.worktopColour.value);
function newTexture() {
var textureName = '<img src="'document.worktopForm.worktopColour.value'.jpg>';
document.getElementById("texture").innerHTML += textureName;
}
<form name="worktopForm">
<label>Choose colour of Worktop (Please select one)</label><br/>
<select name="worktopColour">
<option value="none" selected></option>
<option value="starGalaxy">Star Galaxy (££)</option>
<option value="tanBrown">Tan Brown (£££)</option>
<option value="coolColour">Cool Colour (££££)</option>
<option value="nutYellow">Nut Yellow (£££££)</option>
</select>
<div id="texture"></div></form>
Solution 1:[1]
You can call any function on onchange
event of select
<select id="worktopColour" onchange="newTexture();">
function newTexture() {
var textureName = document.getElementById("worktopColour");
var imagevalue=textureName.options[textureName.selectedIndex].value;
}
Use imagevalue
variable.
Solution 2:[2]
Modified function: jsfiddle
document.worktopForm.worktopColour.onchange =newTexture;
function newTexture() {
var textureName = '<img src="' + this.value + '.jpg">';
document.getElementById("texture").innerHTML += textureName;
}?
Solution 3:[3]
Something like this?
<!DOCTYPE html>
<meta charset=UTF-8><!-- validates as html5 -->
<title>select from list</title>
<script>
function go () {
var e = document.getElementById('worktopColour');
document.getElementById('texture').innerHTML +=
e.options[e.selectedIndex].value+'.jpg <br>';
}
</script>
<form>
<label>Choose colour of Worktop</label><br>
<select id=worktopColour onChange=go()>
<option value=none selected=selected>
<option value=starGalaxy>Star Galaxy (££)
<option value=tanBrown>Tan Brown (£££)
<option value=coolColour>Cool Colour (££££)
<option value=nutYellow>Nut Yellow (£££££)
</select></form>
<div id=texture></div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | |
Solution 3 | BrazFlat |