在javascript函数中反映select状态

时间:2012-10-01 10:41:08

标签: javascript-events html-form javascript

在javascript中你是如何做到的,以便随时可以更改某个功能?我想这样做,当有人从下拉表单中选择一个不同的选项时,将出现所选类型的图像。比如这样:

        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>

3 个答案:

答案 0 :(得分:2)

您可以在[{1}}

onchange事件中调用任何函数
select

使用 <select id="worktopColour" onchange="newTexture();"> function newTexture() { var textureName = document.getElementById("worktopColour"); var imagevalue=textureName.options[textureName.selectedIndex].value; } 变量。

答案 1 :(得分:1)

修改后的功能:jsfiddle

 document.worktopForm.worktopColour.onchange =newTexture;

function newTexture() {

        var textureName = '<img src="' + this.value + '.jpg">';
        document.getElementById("texture").innerHTML += textureName;        
}​

答案 2 :(得分:0)

这样的东西?

<!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>