I have some input fields than I want as an array so that I can view them in a table on my page. I have been able to create an array using .serializeArray()
In this fiddle I have been able to output my array however I want the data to appear as it does in the table I have hard coded at the bottom of the fiddle, where it groups all the instances of Tom and Jerry into one row per id. Accumalating all sales values for that id etc. And I want to sort it by the total sale price column. I am aware of server side techniques to do this however in this case I am looking for a jquery solution. What is the best way to acheive this?
I’m assuming you can rely on the hidden input fields always appearing in groups of four with an
id[],name[],sales[]&price[]for each group, otherwise (obviously) you can’t tell which fields are related. So rather than use.serializeArray(), which returns a single array with all the values, I’d put the ids in their own array, the names in their own, and so forth. Perhaps something like this:Working demo: http://jsfiddle.net/nnnnnn/VNSam/5/
By way of explanation, this line:
…says to get all inputs with
name="id[]", and pass the resulting jQuery object to the$.map()method so that we can get back an array containing just the id values – you can see thatgetVal()is just a simple function that does exactly that. I do the same thing forname[]and the other fields.Note also that the sales and price values are strings when retrieved from the inputs, so I’m using the unary plus operator to convert them to numbers.