首页 > 解决方案 > 从下拉列表中选择多个选项并将所选选项输入到输入字段

问题描述

我希望能够在下拉列表中进行多项选择,并将这些选定的输入写入带有 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>

标签: javascripthtmlcssbootstrap-4

解决方案


如果要将选择写入输入,则需要一个脚本。是否有引导程序,不会影响这一点。

你可以这样做:

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


推荐阅读