2017-06-13 73 views
0

我有簡單的表我想要的是點擊特定的行後獲得該行的值爲incidentId並分配給隱藏的空變量。獲取表單元值使用jQuery的行點擊

我的表

<table class="table table-striped"> 
    <thead style="background-color: #F0F1F2"> 
     <tr> 
     <th>Incident Id</th> 
     <th>Party Name</th> 
     <th>Max Rank</th> 
     <th>Incident Description</th> 
     </tr> 
    </thead> 
    <tbody> 
    <c:forEach items="${incidents}" var="incident"> 
     <tr onclick="changeIncidentValue(this)">         
     <td>${incident.incidentId}</td> 
     <td>xxx</td> 
     <td>${incident.partyNameMaxRank}</td> 
     <td>${incident.incidentDesc}</td> 
     </tr> 
    </c:forEach>       
</tbody> 
</table> 
<input type="hidden" id="incidentId" value=""/> 

js函數

<script> 
    function changeIncidentValue(incidentId){ 
     $('#incidentId').val(incidentId); 
     console.log($('#incidentId').val()); 
    } 
</script> 
+3

具有u試過的東西???你的jQuery代碼在哪裏? –

+0

問題已更新 – Casper

+0

'> –

回答

0

傳遞的incidentId代替this內聯單擊處理

<tr onclick="changeIncidentValue(${incident.incidentId})"> 

,而不是

<tr onclick="changeIncidentValue(this)"> 

或者,當你在路過this,用它與DOM遍歷方法從第一個TD元素的值

function changeIncidentValue(elem){ 
    $('#incidentId').val($(elem).find('td:first').text()); 
} 
0

使用find()eq()從第一列得到incidentId

function changeIncidentValue(ths){ 
    $('#incidentId').val($(ths).find('td:eq(0)').text()); 
    consle.log($('#incidentId').val()); 
} 

或者你可以直接設置incidentId的值onclick事件,如

<tr onclick="$('#incidentId').val(${incident.incidentId})">         
    <td>${incident.incidentId}</td> 
    <td>xxx</td> 
    <td>${incident.partyNameMaxRank}</td> 
    <td>${incident.incidentDesc}</td> 
    </tr> 
+0

試試這個沒有給出任何意義,那麼請解釋一下你的代碼是如何工作的? –

0

https://jsfiddle.net/ew73yjaa/

jQuery的

$('.t').on('click',function(){ 
    console.log($(this).find('td').first().text()); 
    $('#incidentId').val($(this).find('td').first().text()); 
}) 

HTML

<table class="table table-striped"> 
<thead style="background-color: #F0F1F2"> 
    <tr> 
    <th>Incident Id</th> 
    <th>Party Name</th> 
    <th>Max Rank</th> 
    <th>Incident Description</th> 
    </tr> 
</thead> 
<tbody> 
    <tr class="t">         
    <td>1</td> 
    <td>xxx</td> 
    <td>2</td> 
    <td>3</td> 
    </tr>     
</tbody> 
</table> 
<input id="incidentId" value=""/>