假设以下HTML下拉列表:
我正在寻找javascript获得所需的选项文本的基础上,它的值。
比如如果问value=“2”上的文本是什么?答案:“价值2”
我尝试了下面的jquery代码:
null
$(document).ready(function() {
var value = "2";
// I am getting an error as a output on console
var textValue = $("#test").options[value.selectedIndex].text;
console.log(textValue);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="test" name="test">
<option value="0">Select Value...</option>
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
</select>
null
这对你应该管用:
null
$(document).ready(function () {
var value = "2";
// I am getting "0" as a output on console
var textValue = $("#test>option[value=" + value + "]").html();
console.log(textValue);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="test" name="test">
<option value="0">Select Value...</option>
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
</select>