使用javascript获取多个下拉菜单的选项值 [英] Get selected value of option with multiple dropdown menus using javascript
问题描述
我有多个功能,当选择一个选项时,有多个选项需要更新。我还需要通过属性元素传递第三条数据。
I have multiple features that have multiple options that need to be updated when an option is selected. I also need to pass a third piece of data through the attribute element.
.getElementById()
适用于单个下拉菜单,但是当页面上有多个菜单时,该如何使其工作?
.getElementById()
works for a single dropdown menu, but how do I get it to work when there are multiple menus on the page?
我尝试过 var e = document。 getElementsByClassName(testClass);
不起作用。
我还尝试创建 optionsText
& optionsValue
的方式与 optionsFtr
的创建方式相同, var optionsValue = $('option:选择',这个).value;
,那也没有。
I also tried to create optionsText
& optionsValue
in the same way that optionsFtr
is created with var optionsValue = $('option:selected', this).value;
and that didn't work either.
http://jsfiddle.net/8awqLek4/4/
HTML代码
<ul>
<li>
<div class="ftrsTitle">BODY</div>
<select class="testClass" id="testId">
<option>Select</option>
<option ftr="bod" value="blk">Black</option>
<option ftr="bod" value="grn">Kelly Green</option>
<option ftr="bod" value="red">Red</option>
<option ftr="bod" value="roy">Royal</option>
</select>
</li>
<li>
<div class="ftrsTitle">TRIM</div>
<select class="testClass">
<option>Select</option>
<option ftr="trm" value="blk">Black</option>
<option ftr="trm" value="grn">Kelly Green</option>
<option ftr="trm" value="red">Red</option>
<option ftr="trm" value="roy">Royal</option>
</select>
</li>
</ul>
<div id="vars"></div>
Javascript代码
Javascript Code
$(document).ready(function () {
$("select").on('change', function () {
var e = document.getElementById("testId");
var optionsText = e.options[e.selectedIndex].text;
var optionsValue = e.options[e.selectedIndex].value;
var optionsFtr = $('option:selected', this).attr('ftr');
$("#vars").html("<p>optionsText: " + optionsText + "</p><p>optionsValue: " + optionsValue + "</p><p>optionsFtr: " + optionsFtr + "</p>");
});
});
推荐答案
要阅读选择的值,您只需使用 $(本).VAL()
。要选择选项标签,您应该使用 text()
方法。
To read select value you can simply use $(this).val()
. To get selected option label you should use text()
method.
修正代码如下:
$("select").on('change', function () {
var optionsText = $('option:selected', this).text();
var optionsValue = $(this).val();
var optionsFtr = $('option:selected', this).attr('ftr');
$("#vars").html("<p>optionsText: " + optionsText + "</p><p>optionsValue: " + optionsValue + "</p><p>optionsFtr: " + optionsFtr + "</p>");
});
演示: http://jsfiddle.net/8awqLek4/3/
这篇关于使用javascript获取多个下拉菜单的选项值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!