使用 JavaScript 在下拉列表中获取选定的值
演示Demo 使用 JavaScript 在下拉列表中获取选定的值?
<!DOCTYPE html>
<html>
<head>
<title>使用JavaScript在下拉列表中获取选定的值</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.1.0/css/bootstrap.min.css">
<script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/popper.js/1.12.5/umd/popper.min.js"></script>
<script src="https://cdn.staticfile.org/twitter-bootstrap/4.1.0/js/bootstrap.min.js"></script>
</head>
<body>
<div style="text-align: center;margin: 10px;">
<div class="alert alert-success" role="alert">
使用JavaScript在下拉列表中获取选定的值?
</div>
<div class="input-group mb-3" style="width: 450px;">
<div class="input-group-prepend">
<label class="input-group-text" for="inputGroupSelect">Options</label>
</div>
<select class="custom-select" id="inputGroupSelect" onchange="getSelectValue(this);">
<option value="">Choose...</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</div>
</div>
</body>
<script type="text/javascript">
$(function() {
var e = document.getElementById("inputGroupSelect");
e.options[2].selected = true;
// set_select_checked('inputGroupSelect',3);
var strUserValue = e.options[e.selectedIndex].value; // strUserValue 得到的结果使 2
var strUserText = e.options[e.selectedIndex].text; // strUserText 得到的结果使 Two
console.log('下拉框默认选中的值');
console.log('strUserValue: ' + strUserValue);
console.log('strUserText: ' + strUserText);
console.log('-------------------------------------------');
})
/**
* 设置select控件选中
* @param selectId select的id值
* @param checkValue 选中option的值
* 参考:https://blog.csdn.net/woaifen3344/article/details/56018640?fps=1&locationNum=2
*/
function set_select_checked(selectId, checkValue) {
var select = document.getElementById(selectId);
for (var i = 0; i < select.options.length; i++) {
if (select.options[i].value == checkValue) {
select.options[i].selected = true;
break;
}
}
}
function getSelectValue(selectId) {
var e = selectId;
var strUserValue = e.options[e.selectedIndex].value; // strUserValue 得到的是下拉框的值
var strUserText = e.options[e.selectedIndex].text; // strUserText 得到的是下拉框的文本内容
console.log('strUserValue: ' + strUserValue);
console.log('strUserText: ' + strUserText);
console.log('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~');
}
</script>
</html>
参考资料