Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create json object from html table using selected colums using jquery

i was wondering how to parse html table to get json object that i can send via $.post with jquery.

i have a table

<table id="Report">
 <thead>
  <tr>
   <th>Kod</th>
   <th>Nazwa</th>
   <th>Ilość</th>
   <th>Netto / 1szt.</th>
   <th>Suma brutto</th>
  </tr>
 </thead>
<tbody>
 <tr>
  <td>00171 </td>
  <td>SŁUP 50/1800 POŚREDNI(P) </td>
  <td>5</td><td>97.00 PLN </td>
  <td>394.31 PLN </td>
 </tr>
 <tr>
  <td>00172</td>
  <td>SŁUP 50/1800 NAROŻNY(P)</td>
  <td>1</td><td>97.00 PLN</td>
  <td>78.86 PLN</td>
 </tr>
 <tr>
  <td>00173 </td>
  <td>SŁUP 50/1800 KOŃCOWY(P) </td>
  <td>1</td><td>97.00 PLN </td>
  <td>78.86 PLN</td>
 </tr>
</tbody>
<tfoot style="font-weight: bold;">    
 <tr>
  <th colspan="3" style="text-align: right;">Razem netto: 1955.85 PLN</th>
  <th colspan="2" style="text-align: right;">Razem brutto: 2405.69 PLN</th>
 </tr>
 </tfoot>
</table>

and what i need is json object in this format (first <td> and third <td>):

[{"00171":5},
 {"00172":1},
 {"00173":1}
]

and that i can send it via

$.post(  
 "print.php",  
 {json: myjsonvar},  
 "json"  
);

any idea how to do that?

thanks

like image 330
gerpaick Avatar asked Jun 09 '26 06:06

gerpaick


2 Answers

var json = [];
$('#Report').find('tbody tr').each(function(){
    var obj = {},
        $td = $(this).find('td'),
        key = $td.eq(0).text(),
        val = parseInt( $td.eq(2).text(), 10 );
    obj[key] = val;
    json.push(obj);
});
like image 75
Kevin Ennis Avatar answered Jun 11 '26 18:06

Kevin Ennis


How about:

var myjsonvar=[];

$('#Report tbody tr').each(function(){
   var data={};
   var tr=$(this);
   data[tr.find('td:first-child').text()]=tr.find('td:nth-child(3)').text();
   myjsonvar.push(data);
});
like image 37
broesch Avatar answered Jun 11 '26 18:06

broesch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!