javascript - 在 html 表的下一个 td 中显示选定的选项
问题描述
function a()
{
var e2 = document.getElementById("fid");
var strUser2 = e2.options[e2.selectedIndex].text;
document.getElementById("fid2").value=strUser2;
}
<table>
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
</tr>
<tr>
<td><input type="text" name="id1" form="form2" id="id1" class="form-control input-sm" ></td>
<td><select class="form-control" id="fid" name="fid" form="form2" required>
<option value="" selected>Select</option>
<c:forEach var="b" items="${model.list2}">
<option value="${b.id}">${b.name}</option>
</c:forEach>
</select></td>
<td ><input class="form-control" id="fid2" name="fid2" required></td>
</tr>
</table>
表行是动态的。行将根据所做的搜索填充。只有第二列和第三列是可编辑的。第 3 列应包含已在第 2 列中选择的值。此代码仅适用于第 1 行。但它应该适用于所有行。如何实现它。
解决方案
尝试将 select 传递给您的函数,以防止一个 DOM 查询,并将 select 与输入匹配,并将属性名称与 id 匹配。
这样它更清洁,更快,可重复使用。
<table>
<tr>
<th>A</th>
<th>B</th>
</tr>
<tr>
<td><select class="form-control" name="id1" onchange="a( this )" required>
<option selected>Select</option>
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
<option>E</option>
<option>F</option>
</select></td>
<td><input type="text" id="id1"></td>
</tr>
<tr>
<td><select class="form-control" name="id2" onchange="a( this )" required>
<option selected>Select</option>
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
<option>E</option>
<option>F</option>
</select></td>
<td><input type="text" id="id2"></td>
</tr>
</table>
<script>
function a( select ) {
var target = document.getElementById( select.name );
target.value = select.value;
}
</script>
推荐阅读
- arrays - 删除 Double 类型数组中的最小值和最大值
- list - 在列表中保存一定数量的随机海龟
- tensorflow - 使用带有 SavedModel 的 GradientTape 对输入进行梯度下降
- c++ - 使用 std::vector 时如何避免意外的析构函数
- javascript - 如何将带有数组的对象推送到JS中的数组中
- jquery - 使用 Framework7 在预加载器中动态更改文本
- jenkins - 在 Jenkins 中使用 Email-ext 插件在 HTML 页面中打印用户定义的变量
- c - 我正在制作一个质数检查器:当我尝试运行它时,它停止工作
- vb.net - 将 .net 表单作为参数传递给 dll
- powershell - Powershell GET-PSSession 输出用户名作为列表框