首页 > 解决方案 > 在 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 行。但它应该适用于所有行。如何实现它。

标签: javascripthtml

解决方案


尝试将 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>

推荐阅读