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

如何用jQuery创建可动态增减的输入框列表并合并输入值?

jQuery动态输入框列表实现方案

优化后的完整代码

HTML

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<header>
  <h1>I Learn jQuery.</h1>
  <div class="container">
    <div class="Fields"></div>
    <div class="result" style="margin-top:20px;">
      <p>合并后的字符串:<span id="combinedStr"></span></p>
      <p>输入值数组:<span id="valueArray"></span></p>
    </div>
  </div>
</header>

CSS

body {
  font-size: 17px;
  font-family: "Courier New", Courier, monospace;
  background: whitesmoke;
  line-height: 1.5em;
}

header {
  background: rgb(1, 60, 14);
  color: whitesmoke;
  padding: 20px;
  text-align: center;
  border-bottom: 4px rgb(26, 0, 62) solid;
  margin-bottom: 10px;
}

.container {
  margin: auto;
  padding: 10px;
  width: 200px;
}

.Fields {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.Fields input {
  padding: 6px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

JS

$(document).ready(() => {
  // 初始化第一个输入框
  const $fieldsContainer = $('.Fields');
  createInput().appendTo($fieldsContainer);

  // 创建输入框的函数
  function createInput() {
    return $('<input type="text" value="" />')
      .on('input', handleInputChange);
  }

  // 输入框内容变化处理函数
  function handleInputChange() {
    const $currentInput = $(this);
    const inputValue = $currentInput.val().trim();

    // 输入内容时生成新输入框(仅当当前输入有值且后面没有输入框时)
    if (inputValue && !$currentInput.next('input').length) {
      createInput().insertAfter($currentInput);
    }

    // 内容为空时移除输入框(保留至少一个输入框)
    if (!inputValue && $fieldsContainer.children('input').length > 1) {
      $currentInput.remove();
    }

    // 更新结果展示
    updateResult();
  }

  // 合并为单个字符串+存入数组
  function updateResult() {
    const inputValues = $fieldsContainer.find('input')
      .map((index, elem) => $(elem).val().trim())
      .get()
      .filter(val => val); // 过滤空值

    // 合并字符串(用逗号分隔,可按需修改分隔符)
    const combinedStr = inputValues.join(', ');
    $('#combinedStr').text(combinedStr);

    // 存入数组
    $('#valueArray').text(JSON.stringify(inputValues));
  }
});

功能说明

  • 动态生成输入框:无需依赖计数变量,当输入框有内容且后方无其他输入框时,自动创建新输入框,逻辑更简洁可靠。
  • 自动移除空输入框:输入框内容清空时,若不是唯一输入框则自动移除,保证始终保留至少一个输入框供用户使用。
  • 结果实时更新:通过updateResult函数实时收集非空输入值,既能拼接成指定格式的字符串,也能保存为数组,可直接对接后续业务逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 00:54:13