我有一个下拉菜单,显示“ value2”。其ID为“选择”,如下所示。
<select class="selectOneMenu_Medium_class searchField" id="selectBase">
<option value="Select">Select</option>
</select>
option.attr('value', value['value']);
option.text(value['value2']);
option.attr('label', value['value2']);
每当我尝试使用$('#selectBase').val()
检索值时,它都会给我一个值,但我也希望value2
与此一起。有人可以帮我取回value2
吗?
答案 0 :(得分:0)
您可以使用selected
伪选择器和jquery text
方法
$('#selectBase').on('change', function() {
console.log($(this).val());
console.log($("#selectBase option:selected").text());
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="selectOneMenu_Medium_class searchField" id="selectBase">
<option value="Select">Value 2</option>
<option value="Select1">Value 3</option>
</select>
答案 1 :(得分:0)
jQuery实现
$('#selectBase').on('change', function() {
let myValue = $(this).val(),
myLabel = $("#selectBase option:selected").attr("label"),
myText = $("#selectBase option:selected").text();
console.log(
"Value is", myValue, "\n",
"ValueOfAttribute is", myLabel, "\n",
"Text is", myText);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="selectBase">
<option value="Select1" label="myLabel1">Value 1
</option>
<option value="Select2" label="myLabel2">Value 2
</option>
</select>
Java脚本实现
function selectChanged(ref) {
let index = ref.selectedIndex;
let myValue = ref.value;
let myLabel = ref.options[index].getAttribute("label");
let myText = ref.options[index].text;
console.log(
"Value is", myValue, "\n",
"ValueOfAttribute is", myLabel, "\n",
"Text is", myText, "\n", );
}
<select id="myselect" onChange="selectChanged(this)">
<option value="Select1" label="valOfLabel1">Val 1</option>
<option value="Select2" label="valOfLabel2">Val 2</option>
</select>