Reputation: 1462
This might be a trivial question, but I am a bit confused how to extract column data & construct an object.
The table is dynamic in nature, generated based on the data provided.
The format is like this
<tr>
<td> Label </td>
<td>
<input type = "radio" value="yes"/> YES
<input type = "radio" value="no"/> NO
<textarea>
</td>
<td>
<input type = "radio" value="yes"/> YES
<input type = "radio" value="no"/> NO
<textarea>
</td>
// This structure can repeat
...
...
</tr>
// Rows will repeat themselves
I have jotted up this so far
$(function () {
$('#submit').click(function () {
var i = 0;
var t = document.getElementById('table');
$("#table tr").each(function () {
var columns = $(this).find('td');
/* how to extract column data here?, so that I construct
a column object and keep looping for the other columns
});
});
My JSON needs to be like this: [{label:data, isPresent:data, value:data}, {..}, {..}]
I am unable to get the data of both columns () in one go and then loop over the next 2 columns.
Upvotes: 1
Views: 244
Reputation: 161
Judging from your question, I assume you're quite new at jQuery, so I'm gonna give you a simple solution that can be used in a lot of ways.
I advise you to add classes to your HTML. This way, we can identify all the properties of the table row, independent of where the HTML-element is located in the tr-tag or what type of tag the data is placed into:
<tr>
<td class="item-label"> Label </td>
<td>
<input class="item-option-yes" type="radio" value="yes"/> YES
<input class="item-option-no" type="radio" value="no"/> NO
</td>
... other cells with data ...
</tr>
... other rows ...
In your each-function, you can combine the $(this) and the find()-functions to construct your JSON-object
$(function () {
$('#submit').click(function () {
var itemArray = [];
$("#table tr").each(function (index) {
var itemData = {
"label": $(this).find(".item-label").text(),
"isPresent": $(this).find(".item-option-yes")[0].checked,
"value": $(this).find(".some-other-class").text()
};
itemArray.push(itemData);
});
});
For more information about the find, $(this) and each-functions, please check the jQuery website
Upvotes: 1