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

如何使用JavaScript获取自动完成文本框选中值并传入模态框

Fixing Autocomplete Selected Value Sync to Modal

Got it, let's sort out this issue for you! The root problem here is that your current onkeyup event only triggers when the user types via keyboard—but when they select an option from the autocomplete dropdown, this event doesn't fire. That's why you're only capturing manually typed characters instead of the full selected autocomplete value.

Solution: Use the input Event Instead of onkeyup

The input event detects any change to the input's value, including:

  • Typing with keyboard
  • Selecting an autocomplete option
  • Pasting content
  • Using drag-and-drop to add text

Here's your updated code with this fix:

Updated JavaScript

// Sync Client value to modal input
function Client() {
  const sourceInput = document.getElementById('client1');
  document.getElementById('client2').value = sourceInput.value;
}

// Sync Brand value to modal input
function Brand() {
  const sourceInput = document.getElementsByName('brand1')[0];
  document.getElementsByName('brand2')[0].value = sourceInput.value;
}

// Assuming your toggleModal function handles modal visibility (added for context)
function toggleModal() {
  // Your existing modal toggle logic here
}

Updated HTML

<form autocomplete="off" action="/index.html">
  <table>
    <tr>
      <td><label for="client">Client:</label></td>
      <!-- Replace onkeyup with oninput -->
      <td style="padding:5px"><input type="text" id="client1" placeholder="Enter Client" size="40px" oninput="Client();"></td>
    </tr>
    <tr>
      <td><label for="Brand">Brand:</label></td>
      <!-- Replace onkeyup with oninput -->
      <td style="padding: 5px"><input type="text" id="brand" placeholder="Enter Brand" size="40px" name="brand1" oninput="Brand();"></td>
    </tr>
  </table>
  <div>
    <input id="Button1" type="button" value="Preview" class="button" onclick="toggleModal()" />
  </div>
</form>

<!-- Moved modal content outside the form for proper HTML structure -->
<div>
  <h4><label id="lbclient" class="label">*Client:</label><input type="text" id="client2" readonly size="50px" class="textbox-modal"></h4>
  <h4><label id="lbbrand" class="label">*Brand:</label><input type="text" name="brand2" readonly size="50px" class="textbox-modal"></h4>
</div>

Key Notes:

  • I adjusted the HTML to move the modal content outside the <form> tag—this is a best practice since the modal inputs are readonly and don't need to be part of the form submission.
  • The input event ensures that every time the source input's value changes (even via autocomplete selection), the modal input gets updated immediately.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 18:17:39