Comparing 2 tables column values and copying the next column content to the second table
I am comparing between two tables first column each. If there is find a match i am copying the text from the adjacent cell of the first table to the second table. I am able to compare strings and get the value, but finding it difficult to print it in the second table. I am getting the value in the var "replaceText", but how to print it in the second table ?? Please help... Sample code is as follows..
<script type="text/javascript">
jQuery.noConflict();
jQuery(document).ready(function(){
jQuery('.itemname').each(function(){
var itemName = jQuery(this).text();
jQuery('.comparerow').each(function() {
var compareRow = jQuery(this).text();
if (itemName == compareRow) {
var replaceText = jQuery(this).next('td').text();
alert(replaceText);
}
});
});
});
</script>
HTML is as follows
<table width="100%"><thead>
<tr>
<th align="left" >Name</th><th>Description</th></tr></thead>
<tbody>
<tr>
<td class="comparerow">IX0001</td>
<td class="desc">Desc 1 </td>
</tr>
<tr>
<td class="comparerow">IX0002</td>
<td class="desc" >Desc 2 </td>
</tr>
<tr>
开发者_运维知识库<td class="comparerow">IX0003</td>
<td class="desc">Desc 3 </td>
</tr>
<tr>
<td class="comparerow">IX0004</td>
<td class="desc">Desc 4 </td>
</tr>
</tbody>
</table>
<br />
<table width="100%">
<tr>
<th>Name</th><th>Description</th>
</tr>
<tr >
<td class="itemname">IX0001</td><td></td>
</tr>
<tr>
<td class="itemname">IX0002</td><td></td>
</tr>
<tr>
<td class="itemname">IX0003</td><td></td>
</tr>
</table>
You can simplify this overall using the :contains
selector to find your match like this:
jQuery.noConflict();
jQuery(document).ready(function() {
jQuery('.itemname').each(function() {
var itemName = jQuery(this).text();
var match = jQuery('.comparerow:contains("' + itemName + '")');
if(match.length)
jQuery(this).next('td').text(match.next('td').text());
});
});
This loops through each item, looks for a match. If we found a match (.legnth
is > 0) then set the next <td>
text to the match's next <td>
text.
精彩评论