如何实现二手产品提交表单下拉菜单自定义输入并添加为选项
实现自定义产品类别添加功能
第一步:修改HTML结构
在<select id="productCategory">的<br>标签后新增自定义类别输入容器:
<!-- 新增自定义类别输入框,初始隐藏 --> <div id="customCategoryContainer" style="display: none; margin-top: 8px;"> <label for="customCategory">自定义类别:</label><br> <input type="text" id="customCategory" placeholder="输入你的自定义类别"> </div>
第二步:完善JavaScript逻辑
替换原有的createNewCategory函数,并添加回车事件监听和重置逻辑:
// 实现自定义类别添加的函数 function createNewCategory() { const categorySelect = document.getElementById('productCategory'); const customContainer = document.getElementById('customCategoryContainer'); const customInput = document.getElementById('customCategory'); // 选中Custom选项时显示输入框,否则隐藏并清空内容 if (categorySelect.value === 'custom') { customContainer.style.display = 'block'; customInput.focus(); // 自动聚焦输入框,提升操作体验 } else { customContainer.style.display = 'none'; customInput.value = ''; } } // 页面加载完成后绑定回车事件 document.addEventListener('DOMContentLoaded', function() { const customInput = document.getElementById('customCategory'); const categorySelect = document.getElementById('productCategory'); customInput.addEventListener('keydown', function(e) { // 监听回车键 if (e.key === 'Enter') { e.preventDefault(); // 阻止默认表单提交行为,解决回车触发表单的问题 const customValue = customInput.value.trim(); if (!customValue) { alert('请输入有效的类别名称'); customInput.focus(); return; } // 检查是否已存在相同类别(不区分大小写) const isDuplicate = Array.from(categorySelect.options).some(opt => opt.value.toLowerCase() === customValue.toLowerCase() ); if (isDuplicate) { alert('该类别已存在,请选择现有选项'); customInput.focus(); return; } // 创建新选项并添加到下拉框 const newOption = document.createElement('option'); newOption.value = customValue.toLowerCase(); // 统一小写作为提交值 newOption.textContent = customValue; // 显示用户输入的原始内容 categorySelect.appendChild(newOption); categorySelect.value = newOption.value; // 自动选中新添加的类别 // 隐藏输入框并清空内容 customContainer.style.display = 'none'; customInput.value = ''; } }); }); // 更新重置函数,恢复自定义类别初始状态 function resetForm() { resetReviews(); resetSearchTags(); const customContainer = document.getElementById('customCategoryContainer'); const customInput = document.getElementById('customCategory'); const categorySelect = document.getElementById('productCategory'); customContainer.style.display = 'none'; customInput.value = ''; categorySelect.selectedIndex = 0; // 重置下拉框到第一个选项 }
关键功能说明
- 显示/隐藏逻辑:选中
Custom选项时自动显示输入框并聚焦,切换其他选项时隐藏并清空输入内容。 - 阻止回车提交:通过
e.preventDefault()拦截输入框的回车默认行为,避免误触表单提交。 - 重复检测:添加前检查下拉框中是否已有相同类别(不区分大小写),避免重复添加无效选项。
- 重置兼容:在表单重置时恢复自定义输入框的隐藏状态,确保表单回到初始模样。
内容的提问来源于stack exchange,提问作者user27621064
相关产品推荐
相关产品推荐

