[英]select value of dropdownlist item jquery
HTML 的HTML
<select id="selectDepartment">
<option value="1">120</option>
<option value="2">20</option>
<option value="3">140</option>
<option value="4">4120</option>
<option value="5">560</option>
<option value="6">451</option>
<option value="7">310</option>
<option value="8">656</option>
<option value="9">444</option>
<option value="10">555</option>
<option value="11">2560</option>
<option value="12">450</option>
</select>
jQuery jQuery的
$("#selectDepartment").change( function() {
alert($("select option:selected").val());
});
the above function always shows value 1 on alert, when I select any one of the options 当我选择任一选项时,以上功能始终在警报中显示值1
Your method of finding the selection option is vague. 您找到选择选项的方法比较模糊。 You're saying "Grab all
<select>
s". 您说的是“获取所有
<select>
s”。 You then go on to grab the :select
ed option from each of them (of all <select>
s on the page). 然后,您继续从每个(页面上所有
<select>
的)中都<select>
:select
ed选项。 Continued, .val()
takes the first value off the top. 继续,
.val()
将第一个值从顶部.val()
。
Simply put, you're always fetching the selected value of the first <select>
found on the page. 简而言之,您始终会获取页面上第一个
<select>
的选定值。 Assuming #selectDepartment
isn't the first <select>
, your value will never change. 假设
#selectDepartment
不是第一个<select>
,则您的值将永远不变。
Try to keep the scope to within the current <Select>
using this
: 尽量范围保持到内的电流
<Select>
使用this
:
$('#selectDepartment').change(function(){
var selopt = $('option:selected',this);
});
Note that I specify the scope to within the <select>
that triggered the .change()
. 请注意,我将范围指定为触发
.change()
的<select>
。 Also note this really isn't necessary as val()
works just as easily: 还要注意,由于
val()
同样容易工作,因此这实际上不是必需的:
var selopt = $(this).val();
Let jQuery do the heavy lifting. 让jQuery做繁重的工作。 You really only need
option:selected
if you want control over styling that specific element, or you're working with a multi-select and want more control. 实际上,您只需要
option:selected
select即可,如果您想控制特定元素的样式,或者正在使用多选功能并希望获得更多控制权。
You can do something like this: 您可以执行以下操作:
$("#selectDepartment").change( function() {
var selected = $(this).find(":selected");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.