You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将文本框(textbox)的值添加到列表中?附现有多选列表代码

如何将文本框的值添加到下拉多选列表中?

没问题,我来教你一步步实现这个功能~

首先,你得先给页面加个文本框和触发添加的按钮(毕竟原来的代码里没有输入和触发的入口嘛),修改后的HTML结构如下:

<p>Please select :</p>
<!-- 添加文本框用于输入内容 -->
<input type="text" id="inputBox" placeholder="输入要添加的选项内容">
<!-- 添加按钮触发添加操作 -->
<button onclick="addOption()">添加新选项</button>
<select id='pre-selected-options1' multiple='multiple'>
  <option value='elem_1' selected>1</option>
  <option value='elem_2'>2</option>
  <option value='elem_3'>nextoption</option>
  <option value='elem_4' selected>option 1</option>
  <option value='elem_100'>option 2</option>
</select>

接下来写核心的JavaScript逻辑,实现点击按钮后把文本框的内容添加到列表里:

function addOption() {
  // 获取文本框元素和输入的内容(顺便去掉首尾空格)
  const inputElement = document.getElementById('inputBox');
  const inputContent = inputElement.value.trim();
  
  // 先判断用户有没有输入内容
  if (!inputContent) {
    alert('请输入要添加的选项内容哦~');
    return;
  }
  
  // 获取目标下拉列表元素
  const selectElement = document.getElementById('pre-selected-options1');
  
  // 创建一个新的option元素
  const newOption = document.createElement('option');
  // 设置选项显示的文本
  newOption.textContent = inputContent;
  // 设置选项的value值(这里用时间戳生成唯一值,避免和现有value重复)
  newOption.value = `elem_${Date.now()}`;
  
  // 把新选项添加到下拉列表里
  selectElement.appendChild(newOption);
  
  // 清空文本框,方便用户继续输入
  inputElement.value = '';
}

如果你想避免添加重复的选项(比如用户输入了已经存在的内容),可以在代码里加个重复检查的逻辑:

function addOption() {
  const inputElement = document.getElementById('inputBox');
  const inputContent = inputElement.value.trim();
  
  if (!inputContent) {
    alert('请输入要添加的选项内容哦~');
    return;
  }
  
  const selectElement = document.getElementById('pre-selected-options1');
  
  // 检查列表里是否已经有相同文本的选项
  const hasDuplicate = Array.from(selectElement.options).some(option => option.textContent === inputContent);
  
  if (hasDuplicate) {
    alert('这个选项已经存在啦,换个内容试试~');
    inputElement.value = '';
    return;
  }
  
  const newOption = document.createElement('option');
  newOption.textContent = inputContent;
  newOption.value = `elem_${Date.now()}`;
  
  selectElement.appendChild(newOption);
  inputElement.value = '';
}

这样就完成啦,用户输入内容点击按钮,就能把内容添加到你的多选下拉列表里了~

内容的提问来源于stack exchange,提问作者qwww

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:18:51