javascript HTML 组合框所选项目的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26084282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 05:28:43  来源:igfitidea点击:

HTML Combo Box selected Item's value

javascripthtmlcombobox

提问by Dalorzo

Im trying to make this HTML combo box equal to a value.

我试图使这个 HTML 组合框等于一个值。

<select name="file_type"> <option value=".jpg">.JPG</option> <option value=".png">.PNG</option> <option value=".gif">.GIF</option> </select>

<select name="file_type"> <option value=".jpg">.JPG</option> <option value=".png">.PNG</option> <option value=".gif">.GIF</option> </select>

So when i select jpg on my web page, does that mean that file_type = .jpg? I'd think so.

所以当我在我的网页上选择 jpg 时,这是否意味着 file_type = .jpg?我会这么认为。

So then im trying to call that value from javascript, like so:

然后我尝试从 javascript 调用该值,如下所示:

var fileType = document.getElementByID("file_type").value;

var fileType = document.getElementByID("file_type").value;

is that how it is done? How else can I get the value of the selected item in the combo box?

这是怎么做的?我还能如何获取组合框中所选项目的值?

Regards

问候

回答by Dalorzo

First your control has no IDattribute set only name so you need to add the id to the html

首先,您的控件没有ID仅设置名称的属性,因此您需要将 id 添加到 html

<select id="file_type" name="file_type" >

Then the way you get the selected of a combo is like:

那么你选择一个组合的方式是这样的:

var selectCtrl = document.getElementById("file_type");
var selectedItem = selectCtrl.options[selectCtrl.selectedIndex];

This selectedItemhas to properties valueand text:

selectedItem必须是属性value和文本:

selectedItem.value //<--  ".jpg"

and

selectedItem.text //<-- ".JPG"

Online Demo

在线演示