如何从下拉列表复制选中产品对应的price与currency值至文本框?
问题分析与解决方案
你的代码存在几个关键问题导致无法正常工作:
<option>标签内不能嵌套<span>元素,浏览器会忽略这些嵌套标签,导致无法通过DOM获取到price和currency的内容;- 循环生成的每个option里都重复使用了
id="price"和id="currency",HTML中id必须唯一,重复id会导致DOM查询混乱; document.getElementById()只接受一个参数(元素id),你传入的第二个参数无效,无法定位到选中项内的元素。
修正后的代码
HTML部分
<select class="form-control" id="ProductList" onchange="copyValue()"> <option>--- Select Product---</option> @foreach(var item in Model.PL) { <!-- 使用data属性存储price和currency,同时保留显示文本 --> <option value="@item.ProdId" data-price="@item.price" data-currency="@item.currency"> @item.Name - @item.price @item.currency </option> } </select> <input class="form-control" id="pricecopy" /> <input class="form-control" id="currencycopy" />
JavaScript部分
function copyValue() { // 获取选中的option元素 const selectedOption = document.getElementById('ProductList').selectedOptions[0]; // 读取自定义data属性的值 const selectedPrice = selectedOption.dataset.price; const selectedCurrency = selectedOption.dataset.currency; // 赋值到输入框(注意判断是否是默认选项) if (selectedPrice && selectedCurrency) { document.getElementById('pricecopy').value = selectedPrice; document.getElementById('currencycopy').value = selectedCurrency; } else { // 选择默认选项时清空输入框 document.getElementById('pricecopy').value = ''; document.getElementById('currencycopy').value = ''; } }
改动说明
- 移除嵌套span并使用data属性:把price和currency存储在option的
data-price和data-currency自定义属性中,既保留了数据,又符合HTML规范; - 唯一id:删除了重复的id,避免DOM查询冲突;
- 正确获取选中项:通过
selectedOptions[0]获取当前选中的option,再通过dataset读取自定义属性值,逻辑清晰且符合DOM API规范; - 增加默认选项处理:当选择"--- Select Product---"时,清空输入框,提升用户体验。
内容的提问来源于stack exchange,提问作者Fillo
相关产品推荐
相关产品推荐

