[英]Accessing Selected Value from a Pulldown menu
I am having trouble in accessing the selected value from a dropdown menu. 我无法从下拉菜单访问选定的值。 When I try to access the value selected in the javascript function displayPhoto, no value is being accessed at all (I tried to print it out in a textfield).
当我尝试访问在javascript函数displayPhoto中选择的值时,根本没有访问任何值(我试图在文本字段中将其打印出来)。 Am I doing something wrong?
难道我做错了什么? Thanks!
谢谢!
Here is the HTML part: 这是HTML部分:
<form id="colorChoice">
<img id="photo" src="red.jpg" alt="red" />
<select name="color" size=5>
<option value="red" onclick="jsFunction()">Red</option>
<option value="blue" onclick="jsFunction()">Blue</option>
...
</select>
</form>
(I have tried this for 'onclick' and 'onchange' , both doesn't work.) (我已经针对'onclick'和'onchange'尝试了这两种方法,但这两种方法均无效。)
Here is the Javascript part: 这是Javascript部分:
function jsFunction(){
var imageFile; = document.getElementById("colorChoice").color.value + ".jpg";
...
}
You need to put onchange
on the select
element. 您需要在
select
元素上放置onchange
。
<form id="colorChoice">
<img id="photo" src="red.jpg" alt="red" />
<select name="color" id="color" size="5" onchange="jsFunction()">
<option value="red">Red</option>
<option value="blue">Blue</option>
...
</select>
</form>
ther is also a ;
这也是一个
;
in your function infront of imageFile 在imageFile的函数前面
function jsFunction(){
var imageFile = document.getElementById('color').value + '.jpg';
alert(imageFile);
}
Your Html Part be like that 您的HTML部分就是这样
<form id="colorChoice">
<img id="photo" src="red.jpg" alt="red" />
<select name="color" size="5" onchange="jsFunction()">
<option value="red">Red</option>
<option value="blue">Blue</option>
...
</select>
</form>
and you jscript part would be like that 而你的jscript部分会是这样的
function jsFunction(){
var imageFile = document.getElementById("colorChoice").color.value + ".jpg";
...
}
You cannot select an item by "name" attribute when you are using getElementById. 使用getElementById时,无法通过“名称”属性选择项。 Rather set an ID for the select tag, like so:
而是为select标签设置一个ID,如下所示:
<form id="colorChoice">
<img id="photo" src="red.jpg" alt="red" />
<select id="color" size="5" onchange="jsFunction()">
<option value="red">Red</option>
<option value="blue">Blue</option>
...
</select>
</form>
And then have your js as follows: 然后将您的js如下所示:
function jsFunction(){
var imageFile = document.getElementById("color").value + ".jpg";
...
}
Also note that I have taken the onchange() event as the above answers suggest. 还要注意,正如上面的答案所暗示的,我已经采用了onchange()事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.