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

如何将文本输入框替换为下拉选择框并复用原有JavaScript逻辑?

Got it, here's exactly what you need to do to swap out that text input for your dropdown while keeping the existing JavaScript logic intact:

Solution
  • Replace your original text input with the <select> element, making sure to add the id="myInput1" attribute to the <select> tag. This ensures your existing JavaScript that uses document.getElementById("myInput1").value will still work perfectly—it’ll now retrieve the value of the selected option instead of a text input’s value.

Here's the modified HTML code:

<select id="myInput1" style="z-index:1">
  <option value="0">Select car:</option>
  <option value="1">Audi</option>
  <option value="2">BMW</option>
  <option value="3">Citroen</option>
  <option value="4">Ford</option>
  <option value="5">Honda</option>
  <option value="6">Jaguar</option>
  <option value="7">Land Rover</option>
  <option value="8">Mercedes</option>
  <option value="9">Mini</option>
  <option value="10">Nissan</option>
  <option value="11">Toyota</option>
  <option value="12">Volvo</option>
</select>
<span onclick="newElement1()" class="addBtn" style="border-radius: 0px; height:30px">Add</span>

Quick Notes:

  • I moved the style="z-index:1" from your original input to the <select> to maintain the same visual stacking context.
  • Your original JavaScript will automatically pull the selected option’s value (e.g., selecting "Audi" will return "1" via document.getElementById("myInput1").value), which matches how it previously retrieved the text input’s value.
  • If you ever need to get the display text of the selected option instead of the numeric value, you could use this snippet (though it’s not needed for your existing logic):
    const selectElement = document.getElementById("myInput1");
    const selectedText = selectElement.options[selectElement.selectedIndex].text;
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:46:23