lightswitch05 / table-to-json

Serializes HTML tables into JSON objects.
http://lightswitch05.github.io/table-to-json/
MIT License
756 stars 172 forks source link

Clone Table not working #24

Closed ammar91 closed 8 years ago

ammar91 commented 8 years ago

I have a table in my view but that's all contain input inside td element. If I directly try to call tableToJSON on my table, the json it produce contain empty values..So what I am trying to do is to clone the actual table and change the input field to plain text and then call tableToJSON on that clone variable but it produces empty array.. But If I use the actual table it works but that actually make changes visually as well which I really don't want...My code looks like this:

    var tempTable = $('#schedules table').clone();
    tempTable.find('tbody tr').each(function (index, tr) {
        $(this).find('td').each(function (tdIndex, td) {
            $(this).text($(this).find('input').val());
        })
    });

    var json = tempTable.tableToJSON({
        ignoreEmptyRows: true,
        headings: ["Type", "SubType", "ProductId", "QtyMin", "QtyMax", "Pricing"]
    });

    console.log(json); //produces empty array
lightswitch05 commented 8 years ago

tableToJson was not made to support calling directly on objects. The only way to use table to json is with a selector: $('#schedules table'). tableToJSON()

If you update this Plunker template with your HTML and tell me what you are expecting your JSON to look like, then I can try to help: http://plnkr.co/edit/iQFtcEEZkvsMJ2UqcrlW

ammar91 commented 8 years ago

Thanks for your attention. I updated plunkr and that is how my html look like. But with this markup I can't convert it to json as it produces empty strings..

lightswitch05 commented 8 years ago

Please provide me with the link of the updated plunker

ammar91 commented 8 years ago

http://plnkr.co/edit/EuuYMpk0MXIFNr3tNTbT

lightswitch05 commented 8 years ago

TableToJSON is not meant to work with <input> tags. In the next version, I might add some support for data manipulation - but there are no immediate plans. Please refer to this StackOverflow answer on how to build a javascript object to represent your table of inputs: http://stackoverflow.com/a/18133864/912563

Mottie commented 8 years ago

Actually, that is what the textExtractor is for (demo)

$('#run').click( function() {
    var table = $('#students').tableToJSON({
      textExtractor : function(cellIndex, $cell) {
        // get value from the input inside table cells;
        // if empty or non-existant, get the cell text
        return $cell.find('input').val() || $cell.text();
      }
    });
    alert(JSON.stringify(table));  
});
lightswitch05 commented 8 years ago

Oh fantastic, thanks @Mottie