Stacker Stacker - 6 months ago 10
Javascript Question

How can I stringify (JSON) a table when I have a <select> dropdown in the table?

I am trying to use JSON to pull what is selected in a table and populate an array which I can then push into a sharepoint list. What I'm getting at the moment pulls all data from the select list.

I have the following function:


Script:


<script>
$(document).ready(function () {
$('#clicker').on('click', function (e) {
var tableToObj = function (table) {
var trs = table.rows,
trl = trs.length,
i = 0,
j = 0,
keys = [],
obj, ret = [];
for (; i < trl; i++) {
if (i == 0) {
for (; j < trs[i].children.length; j++) {
keys.push(trs[i].children[j].innerHTML);
}
} else {
obj = {};
for (j = 0; j < trs[i].children.length; j++) {
obj[keys[j]] = trs[i].children[j].innerHTML;
}
ret.push(obj);
}
}
return ret;
};
document.getElementById('r').innerHTML = JSON.stringify(tableToObj(document.getElementsByTagName('table')[0]));
});
});
</script>



HTML


<table>
<tr><td>id</td><td><select><option value="1">1</option><option value="2">2</option></select></td><td>value2</td></tr>
<tr><td>0</td><td>0</td><td>0</td></tr>
<tr><td>0</td><td>1.5</td><td>2.15</td></tr>
</table>
<button id="clicker">Button</button>
<br />
Result:
<div id="r"></div>


Edit: Fiddle: https://jsfiddle.net/naLfud1f/3/

The output I am expecting is for it to pick up the value I choose in the select box, rather than both of them. e.g.

[{"id":"0","":"0","2":"0"},{"id":"0","":"1.5","2":"2.15"}]


or

[{"id":"0","":"0","1":"0"},{"id":"0","":"1.5","1":"2.15"}]


rather than both 1 and 2

Answer

Adding an if statement in one of the loops...

var sel = $(trs[i].children[j]).find("select");
if (sel.length == 0) {
    keys.push(trs[i].children[j].innerHTML);
} else {
    keys.push(sel.val());
}

It generates this result:

[{"1":"0","id":"0","value2":"0"},
 {"1":"1.5","id":"0","value2":"2.15"}]

Demo. Is that what you want ?

Comments