Javascript 为什么我没有使用 Select 从 onChange 获取值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3597456/
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
Why am I not getting the value from onChange with Select?
提问by dcp3450
Testing part of a form. So, right now I just want to alert what the user selects:
测试表单的一部分。所以,现在我只想提醒用户选择什么:
JS:
JS:
function getData(title)
{
alert(title);
}
HTML generated by PHP:
PHP 生成的 HTML:
<select name="currentList" onChange="getData(this);">
<option value="hat">Hat</option>
<option value="shirt">Shirt</option>
<option value="pants">Pants</option>
</select>
when I change the value I get an alert with:
当我更改值时,我收到一条警报:
[object HTMLSelectElement]
[对象 HTMLSelectElement]
回答by meder omuraliev
try alert(this.value)
尝试 alert(this.value)
回答by BalusC
With thisyou're passing the HTML select elementto the function, not the value of the selected option. To obtain the value of the selected option, you need to get the selected option from the optionsby selectedIndexand then get its value. In a nutshell:
随着this您将HTML 选择元素传递给函数,而不是所选选项的值。要获取选中选项的值,需要从optionsby 中获取选中的选项selectedIndex,然后获取其value. 简而言之:
function getData(dropdown) {
var value = dropdown.options[dropdown.selectedIndex].value;
alert(value);
}
回答by Ian Davis
With jQuery, you could be concise with alert($("#currentList").val());, as long as you add the id="currentList" to the select list. This way you don't have to pass "this" to the onchange function.
使用 jQuery,您可以使用 alert($("#currentList").val()); 简洁,只要您将 id="currentList" 添加到选择列表。这样您就不必将“this”传递给 onchange 函数。
回答by dennis23
You can try
你可以试试
alert(title.value)

