javascript - 从下拉列表中选择多个选项并将所选选项输入到输入字段
问题描述
我希望能够在下拉列表中进行多项选择,并将这些选定的输入写入带有 HTML、CSS 和 JS 的输入字段。我正在使用引导程序,这是我到目前为止所得到的,但还没有找到如何选择多个项目并将这些选择写入输入字段。我试过<select multiple>
但似乎没有用。
索引.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Nestia Umbrella</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<link rel="stylesheet" href="./app.css">
<script src="https://kit.fontawesome.com/86fa3c1316.js" crossorigin="anonymous"></script>
</head>
<body>
<div class="input-group">
<select class="custom-select" id="inputGroupSelect04" aria-label="Example select with button addon" placeholder="Services Rendered">
<option value="General Cleaning">General Cleaning</option>
<option value="Change Battery">Change Battery</option>
<option value="Re-align Spring">Re-align Spring</option>
<option value="Replace Spring">Replace Spring</option>
<option value="Replace Battery Cover Screw">Replace Battery Cover Screw</option>
</select>
</div>
</body>
</html>
解决方案
如果要将选择写入输入,则需要一个脚本。是否有引导程序,不会影响这一点。
你可以这样做:
var select = document.getElementById("inputGroupSelect04");
var input = document.getElementById("input");
select.addEventListener("change", function(event) {
const selected = document.querySelectorAll('#inputGroupSelect04 option:checked');
const values = Array.from(selected).map(el => el.value);
input.value = values.join(', ');
})
我在这里创建了一个示例: https ://codepen.io/bj-rn-nyborg/pen/WNGNwpV
推荐阅读
- sql - SQL Server 错误:948:数据库无法打开,因为它的版本是 896。此服务器支持版本 782 或更早版本?
- php - Nginx 404 上的 Laravel
- node.js - 访问 Windows 上传文件对话框
- .net - Access-Control-Max-Age 的最大值和默认值
- android - 将 infoWindow 放置在远离重叠多段线的位置
- c - 多线程程序中执行的线程顺序
- python - 调用“打印”时缺少括号
- business-process-management - 如何在 Workfusion RPA Express 中将变量值从一个机器人任务传输到另一个机器人任务?
- java - 与迭代器一起使用时,openCSV CSVReader getRecordsRead 方法返回错误计数
- maven - Mulesoft Munit Maven 构建失败