javascript 选择下拉选项时显示文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11888823/
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
Show text when a dropdown option is selected
提问by AnchovyLegend
I am trying to figure out a way to display a some text based on the drop down item selected by the user, in the "result" div below. I know how to do this with a normal input field but I am having trouble understanding how to pass in "option values" into the javascript function. This is what I tried so far...
我试图找出一种方法,根据用户选择的下拉项目在下面的“结果”div 中显示一些文本。我知道如何使用普通输入字段执行此操作,但我无法理解如何将“选项值”传递到 javascript 函数中。这是我迄今为止尝试过的...
In the code below, I am simply trying to successfully pass whatever drop down item value is selected into the javascript function and print out the name of that value in the "result" div... once I am able to do that, I will implement the 'tip' feature described above.
在下面的代码中,我只是想成功地将选择的任何下拉项目值传递到 javascript 函数中,并在“结果”div 中打印出该值的名称......一旦我能够做到这一点,我就会实现上面描述的“提示”功能。
My Markup:
我的标记:
<select onChange="dropdownTip(this.value)" name="search_type" style="margin-right:10px; margin-top:2px;">
<option selected="selected" value="fruit_search">fruits</option>
<option value="veggies_search">veggies</option>
<option value="animals_search">animals</option>
<option value="all_search">all</option>
</select>
<div id="result"></div>
My JavaScript:
我的 JavaScript:
<script type="text/javascript">
function dropdownTip(value){
document.getElementByID("result").innerHTML = value;
}
</script>
回答by codisfy
Is this what you wanted? check the fiddle below
这是你想要的吗?检查下面的小提琴
回答by PitaJ
Try this:
试试这个:
<select onChange="dropdownTip()" id="select" name="search_type" style="margin-right:10px; margin-top:2px;">
<option selected="selected" value="fruit_search">fruits</option>
<option value="veggies_search">veggies</option>
<option value="animals_search">animals</option>
<option value="all_search">all</option>
</select>
<div id="result"></div>
<script type="text/javascript">
function dropdownTip(){
var value = document.getElementById('select').value;
document.getElementByID("result").innerHTML = value;
}
</script>