如何将文本输入框替换为下拉选择框并复用原有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 theid="myInput1"attribute to the<select>tag. This ensures your existing JavaScript that usesdocument.getElementById("myInput1").valuewill still work perfectly—it’ll now retrieve thevalueof 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"viadocument.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
相关产品推荐
相关产品推荐

