2

I have the following table, which contains selectboxes, and I want to create a JSON string. I tried several code snippets but none gave me a correct output. The output I want to have should be like:

id[0]: start time: 12:34;end time: 15:00
id[1]: start time: 18:14;end time: 18:17

etc

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

<script language="Javascript">

function addRowEntry(tableID){
        var table = document.getElementById(tableID);
        var rowCount = table.rows.length;
        var row = table.insertRow(rowCount);
        var colCount = table.rows[1].cells.length;
        for(var i=0; i<colCount; i++) {
            var newcell = row.insertCell(i);
            newcell.innerHTML = table.rows[1].cells[i].innerHTML;
        }
      }



</script>

<table id="dynTable" name="dynTable" border=0 width="200px"> 
<thead>
<tr height="50" id="header">

    <td class="datacell"  align="center">Heure Start</td>

    <td class="datacell"  align="center">Min Start</td>
    <td class="datacell"  align="center">Heure End</td>

    <td class="datacell"  align="center">Min End</td>
    <td class="datacell" ><input type="button" value="Ajouter" name="add" id="add" style="width:50px" onclick="addRowEntry('dynTable');"/></td>
</tr>
</thead>    
<tbody>
<tr id="TimeSel">
<td class="datacell" >
    <select id="openH" name="openH">
        <option></option>
        <?php 
            for ($i=0;$i<24;$i++) {
                echo "<option id=$i>";
                echo $i;
                echo "</option>";
            }
        ?>
    </select>
</td>

<td class="datacell" >
    <select id="openM" name="openM">
        <option></option>
        <?php 
            for ($i=0;$i<60;$i++) {
                echo "<option id=$i>";
                echo $i;
                echo "</option>";
            }
        ?>
    </select>
</td>
<td class="datacell" >
    <select name="closeH" id="closeH">
        <option></option>
        <?php 
            for ($i=0;$i<24;$i++) {
                echo "<option id=$i>";
                echo $i;
                echo "</option>";
            }
        ?>
    </select>
</td>

<td class="datacell" >
    <select name="closeM" id="closeM">
        <option></option>
        <?php 
            for ($i=0;$i<60;$i++) {
                echo "<option id=$i>";
                echo $i;
                echo "</option>";
            }
        ?>
    </select>
</td>
</tbody>
</tr>

</table>

<input type="button" id="AddDateTime" name="AddDateTime" value="OK" onclick="tableToJson('dynTable');"></input>

Edit: I deleted the include file. Was jused for some tests:

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user2718058
  • 21
  • 1
  • 3

3 Answers3

1

Use

var val=JSON.stringify(value);

in a for loop to capture each element of the array while you are traversing the table. That way you automatically get the required output in JSON format.

EDIT: (using jQuery):

var myRows = [];
var $headers = $("th");
var $rows = $("tbody tr").each(function(index) {
  $cells = $(this).find("td");
  myRows[index] = {};
  $cells.each(function(cellIndex) {
    myRows[index][$($headers[cellIndex]).html()] = $(this).html();
  });    
});

var myObj = {};
myObj.myrows = myRows;
alert(JSON.stringify(myObj));​ // to test the output
George Violaris
  • 315
  • 1
  • 10
  • Thanks George, but there's my problem ... how do I loop thru a table and get the selection options ? – user2718058 Aug 26 '13 at 14:40
  • See my edit above, hope that helps, got the code for looping from here http://stackoverflow.com/questions/9927126/how-to-convert-the-following-table-to-json-with-javascript – George Violaris Aug 26 '13 at 15:29
  • Hi George, thanks for your help, I tried your code, but it gives me the html code for all select boxes and not the selected option – user2718058 Aug 26 '13 at 16:17
0

I have used the .val() function on the jQuery host object for each select element to get the initial value of the selected option element. Since you have not specified a value attribute, the initial value of each option element is set to the contents of the element (from the HTML 4.01 Spec).

JavaScript

function getJSONfromTable(tableID) {

  var res = [];

  // function now expects an id string passed
  $('tbody tr', '#' + tableID).each(function() {
    var $this = $(this);

    res.push({
      'openH' : parseInt($this.find('#openH').val(), 10),
      'openM' : parseInt($this.find('#openM').val(), 10),
      'closeH': parseInt($this.find('#closeH').val(), 10),
      'closeM': parseInt($this.find('#closeH').val(), 10)
    });
  });

  return JSON.stringify(res);

}

// Example
var json = getJSONfromTable('dynTable');

// Returns (example):
//=> "[{"openH":1,"openM":3,"closeH":6,"closeM":24}, "openH":4,"openM":2,"closeH":12,"closeM":19}]"

A suggestion

You may or may not be bothered by this but the duplicate id attributes you're declaring for each set of option elements is invalid according to the HTML spec.

(id) This attribute assigns a name to an element. This name must be unique in a document.

cjross
  • 636
  • 1
  • 5
  • 10
  • how should I modify the ID so it will be correct even after inserting new rows ? – user2718058 Aug 26 '13 at 16:18
  • @user2718058 i updated it to add a hash sign to the string you pass into the function. should work now. which ID are you wanting to modify? the `tr` attribute or the `option` attributes? – cjross Aug 27 '13 at 03:30
0

This is almost an exact duplicate of Html table to array of json. In which, the asker has an HTML table of input fields. The HTML table is dynamic, where there can be any number of rows and columns with inputs.

The solution wraps the entire <table> in a <form>, serializes that form, and then loops through the serialization to put it into a more desired format.

Some issues with your code, you are going to have duplicate IDs for your <option> tags, which is bad. Also, you are closing your </tbody> before you close your </tr>, which is also wrong.

Community
  • 1
  • 1
lightswitch05
  • 9,058
  • 7
  • 52
  • 75