问题
I have an HTML Table that looks like this:

The user can update any of the textboxes and select from the dropdowns.
Once he has completed his actions, The data needs to be sent via ajax to the server.
It is acceptable to send all values (Not only those that changed).
Need help building the JSON string for an ajax transaction.
(Note that the description column can be either a string, textbox or a dropdown in addition the dropdowns do not contain the same options.)
The structure I am trying to map to looks like this:
[
{ id: "1" , desc: "Lenovo" , remark: "International" },
{ id: "2" , desc: "Hard Disks", remark: "" },
{ id: "3" , desc: "T400", remark: "Old Model" },
{ id: "4" , desc: "Poker", remark: "" }
]
Thanks a lot, if map can't do it, I am open to other options.
Be happy and enjoy life ;-)
Post acceptance note:
There is a hidden column between the feature and the description. This is why the indices in the answer are refereeing to cells[2] and cells[5].
回答1:
This should do it for you.
It selects the rows, takes a .slice() of all but the first, then calls .map() to create your Array. The .get() actually pulls the Array out of the jQuery object.
Inside .map(), I used DOM API properties and methods since it just seemed a little simpler (and faster) in this case.
var ProductFeatures = $('#FeatureListTable tr').slice(1).map(function() {
return {
id: this.id,
desc:this.cells[ 2 ].innerHTML,
remark:this.cells[ 5 ].getElementsByTagName('input')[0].value
}
}).get();
If you know there won't be any whitespace inside the 6th cell (remark), you could change this line:
remark:this.cells[ 5 ].getElementsByTagName('input')[0].value
...to this:
remark:this.cells[ 5 ].firstChild.value
EDIT: As a side note, if you are able to change the HTML, I'd wrap the first row in a <thead>
element, then the remaining rows in a <tbody>
element to give separation to the different parts of the table.
Then you could change this:
$('#FeatureListTable tr').slice(1)
...to this:
$('#FeatureListTable > tbody > tr')
...giving you the ability to select all except for the header row without the need for a separate .slice() call to remove the header from the set.
来源:https://stackoverflow.com/questions/4614202/jquery-map-for-an-html-table-help-needed