如何使用 javascript 获取 Select 的显示值
How to get the display value of Select using javascript
<Select>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</Select>
我正在使用document.getElementById("Example").value;
来获取值。
我想显示文本而不是值。 value=1 --> One
.如何获取One
文本?
在普通的JavaScript中,你可以这样做:
const show = () => {
const sel = document.getElementById("Example"); // or this if only called onchange
let value = sel.options[sel.selectedIndex].value; // or just sel.value
let text = sel.options[sel.selectedIndex].text;
console.log(value, text);
}
window.addEventListener("load", () => { // on load
document.getElementById("Example").addEventListener("change",show); // show on change
show(); // show onload
});
<select id="Example">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
j查询:
$(function() { // on load
var $sel = $("#Example");
$sel.on("change",function() {
var value = $(this).val();
var text = $("option:selected", this).text();
console.log(value,text)
}).trigger("change"); // initial call
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="Example">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
在这里,当页面加载时,所选的文本和值是使用 jquery 获取
的$(document).ready(function () {
var ddlText = $("#ddlChar option:selected").text();
var ddlValue = $("#ddlChar option:selected").val();
});
参考这个
http://csharpektroncmssql.blogspot.in/2012/03/jquery-how-to-select-dropdown-selected.html
http://praveenbattula.blogspot.in/2009/08/jquery-how-to-set-value-in-drop-down-as.html
这很好用
jQuery('#Example').change(function(){
var value = jQuery('#Example').val(); //it gets you the value of selected option
console.log(value); // you can see your sected values in console, Eg 1,2,3
});
相关文章:
- 在select元素中显示highchart dashstyle(svg)
- jQuery动态表单显示在select选项上
- 如果选择了当前年份,则在Select元素中仅显示当前和未来月份
- 无法使用angularjs突出显示select标记中的值
- 当Select(选择)显示'其他'只使用CSS
- 从服务器获取数据,并使用$http服务和ng-change在select事件上显示它
- 从select中选择一个选项,然后使用Codeigniter在另一个选择框上显示数据
- jQuery如何显示/隐藏Select by Select
- select选项在angularjs中不显示
- jQuery使用select显示/隐藏
- 角度 ui-select 绑定到一个属性,但向用户显示另一个属性
- 使用 javascript 通过 select 显示表
- 如何显示下拉 Angularjs-ui-select onclick on 超链接标签
- 如何显示uI-select(angularjs)时,单击html元素
- range.select 在 IE10 上无法正确突出显示文本
- ngOptions不显示select元素中的任何选项
- 没有显示select中的数据
- 浏览器不显示SELECT标记内列表文本的空格
- 显示Select Options时的JavaScript事件
- 我无法在JavaScript中显示select的值