javascript - Jquery - Sum of each same class li value -


currently i'm developing invoice app php , mysql & jquery. want show details jquery. have dynamically created tables dynamic data.

<table class="report_table">     <tr>         <td class="items_id">             <ul>                 <li class="kktf0">kktf0</li>                 <li class="pen01">pen01</li>             </ul>         </td>         <td class="items_qty">             <ul>                 <li class="kktf0">1</li>                 <li class="pen01">2</li>             </ul>         </td>     </tr> </table> <table class="report_table">     <tr>         <td class="items_id">             <ul>                 <li class="bkk01">bkk01</li>                 <li class="kktf0">kktf0</li>                 <li class="pen01">pen01</li>             </ul>         </td>         <td class="items_qty">             <ul>                 <li class="bkk01">4</li>                 <li class="kktf0">2</li>                 <li class="pen01">3</li>             </ul>         </td>     </tr> </table> 

li classes dynamically created. jquery code

 jquery(document).ready(function() {     $('.report_table').each(function() {         $('.items_id ul li').each(function() {             $(this).addclass($(this).text());             var classname = $(this).attr("class");             $(this).parents('tr').find('td.items_qty li').eq($(this).index()).addclass(classname);         });     }); }); 

i want result

<table>     <tr>         <th>item id</th>         <th>sum of item</th>     </tr>     <tr>         <td>kktf0</td>         <td>3</td>     </tr>     <tr>         <td>pen01</td>         <td>5</td>     </tr>     <tr>         <td>bkk01</td>         <td>4</td>     </tr> </table> 

i don't have idea. please me... thanks.

pretty short solution:

var data = {}; $('.report_table .items_qty li').each(function() {     data[this.classname] = (data[this.classname] || 0) + +$(this).text(); });  var table = '<table class="result"><tr><tr><th>item id</th><th>sum of item</th></tr>' +  $.map(data, function(qty, key) {     return '<td>' + key + '</td><td>' + qty + '</td>'; }).join('</tr><tr>') + '</tr></table>'; 

http://jsfiddle.net/vf7bz/

brief explanation:

1). each collects data object:

{"kktf0":3,"pen01":5,"bkk01":4}  

2). map creates array:

["<td>kktf0</td><td>3</td>","<td>pen01</td><td>5</td>","<td>bkk01</td><td>4</td>"] 

3). array items joined string using </tr><tr> separator.


Comments

Popular posts from this blog

node.js - Bad Request - node js ajax post -

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -