如何点击HTML行,然后在输入文本中显示行的选择值?
我尝试过这样,但是即使我点击了第二行,输入文本中只出现了第一行,依此类推......
div class="col-md-1 col-md-1 col-xs-1">
<button type="button" class="btn btn-default btn-xs" data-toggle="modal" data-target="#myModal">...</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" scrollY:380>
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Category</h4>
</div>
<div class="modal-body">
<table id="datatable-responsive" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%">
<thead>
<tr>
<th>Id Event Category</th>
<th>Event Category</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<% objLOV.forEach(function (lov) { %>
<tr>
<td id="field_id" onclick="myFunction()">
<%= lov.id %>
</td>
<td id="field_category" onclick="myFunction()">
<%= lov.event_category %>
</td>
<td id="field_description" onclick="myFunction()">
<%= lov.description %>
</td>
</tr>
<% }) %>
</tbody>
</table>
和我的javascript
<script>
function myFunction() {
document.getElementById("id_type").value = document.getElementById("field_id").textContent.trim();
document.getElementById("event_category").value = document.getElementById("field_category").textContent.trim();
document.getElementById("description").value = document.getElementById("field_description").textContent.trim();
}
</script>
"id_type" , "event_category" , "description"
是我的输入文字类型ID
答案 0 :(得分:1)
为click
应用<tr>
事件,并将当前引用this
传递给调用函数<tr onclick="callme(this)">
。从javascript获取当前行引用并找到其中的所有td
。现在使用innerHTML
获取值并将其分配给相应的输入字段(“id_type”,“event_category”,“description”)。请看下面的例子。
function callme(e)
{
var tds=e.getElementsByTagName('td');
document.getElementById("id_type").value = tds[0].innerHTML.trim();
document.getElementById("event_category").value = tds[1].innerHTML.trim();
document.getElementById("description").value = tds[2].innerHTML.trim();
}
<table>
<tr onclick="callme(this)">
<td>test1</td>
<td>something1</td>
<td>content1</td>
</tr>
<tr onclick="callme(this)">
<td>test2</td>
<td>something2</td>
<td>content2</td>
</tr>
<tr onclick="callme(this)">
<td>test3</td>
<td>something3</td>
<td>content3</td>
</tr>
</table>
<input type="text" id="id_type" />
<input type="text" id="event_category" />
<input type="text" id="description" />
注意:根据我的评论,请勿对所有id
使用相同的td
。您可以尝试使用class
代替td
。对于这个当前的解决方案,它不会影响,但在功能上它会像你的代码一样给你错误的信息。重要的是id
应该是唯一的。
答案 1 :(得分:0)
根据HTML规范id
属性在页面中应该是唯一的
因此,如果您有多个具有相同id
的元素,则您的HTML无效。
getElementById()
应该只返回一个元素。你不能让它返回多个元素。
因此,您可以为每一行使用唯一的id
,或尝试使用class