问题:
I have a drop down which displays 'value2'. Its id is "select" like below.
<select class="selectOneMenu_Medium_class searchField" id="selectBase">
<option valu...
可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
I have a drop down which displays 'value2'. Its id is "select" like below.
<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']);
Whenever I try to retrieve the value using $('#selectBase').val()
it gives me a value, but I want value2
also along with this. Can someone helps me in fetching value2
?
回答1:
You can use selected
psuedo selector and jquery text
method
$('#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>
回答2:
JQuery Implementation
$('#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-Script Implementation
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>