• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 797
  • Last Modified:

Traverse table using JQuery / JavaScript concatenating input values

Using Asp.Net and JQuery I have a page containing a table which has had rows dynamically added using JQuery.  Each row contains 14 text inputs each in a seperate <td>.  When the user clicks the save button I need to send this information back to the server.  I have decided the best way is to tuck the data into a comma-delimited hidden field (if there is a better method I'd be pleased to hear about it!).

To do this I expect to use JQuery to traverse the table and concatenate all the values of each row's text fields.  How can I do this?  The table structure is:

<table id="DetailsTable" class="OrderDetails" >
	<tr class="DetailHeader">
		<td  class="SummaryField">Price<br />Over</td>
		<td  class="SummaryField">Std<br />Price</td>
		<td  class="SummaryFieldWide">Total<br />Cost</td>
		<td  class="SummaryField">Total<br />Qty</td>		
		<td  class="SizeField">1</td>
		<td  class="SizeField">2</td>
		<td  class="SizeField">3</td>
		<td  class="SizeField">4</td>
	</tr>    
	<tr id="TemplateHeaderRow" class="SpecHeader">
		<td colspan="30"><label id="LabelProduct"></label></td>
		<td colspan="13" class="RemoveButton"><input id="ButtonRemove" name="ButtonRemove" tabindex="-1" type="button" value="Remove" />	</td>
	</tr>
	<tr id="TemplateDetailRow"  class="DetailLine">
		<td class="PriceOverride"><input id="TextPriceOverride" type="text" tabindex="-1"" name="TextPriceOverride"/></td>
		<td class="SummaryField"><label id="LabelStdPrice"></label></td>
		<td class="SummaryFieldWide"><label id="LabelTotalCost"></label></td>
		<td class="SummaryField"><label id="LabelTotalQty"></label></td>
		<td class="DataField"><input type="text" id="Size_0_1_0" name="Size_0_1_0"/></td>
		<td class="DataField"><input type="text" id="Size_0_2_0" name="Size_0_2_0"/></td>
		<td class="DataField"><input type="text" id="Size_0_3_0" name="Size_0_3_0"/></td>
		<td class="DataField"><input type="text" id="Size_0_4_0" name="Size_0_4_0"/></td>
		<td class="DataField"><input type="text" id="Size_0_4_5" name="Size_0_4_5"/></td>
	</tr>
</table>

Open in new window

0
canuckconsulting
Asked:
canuckconsulting
  • 3
  • 3
  • 2
2 Solutions
 
Julian HansenCommented:
Why not put the table inside a form element and then use JQuery serialize to get the data.
0
 
canuckconsultingAuthor Commented:
I'm happy with that!  Will this let me pluck out just the values I need?  I've not used serialize before so unsure how it will treat the other elements (lables, etc) and inputs (buttons).
0
 
Julian HansenCommented:
It will serialise all input values into an object that can be used with the AJAX functions to send back to a server script.

Alternatively you can right your own serialize by giving the new row inputs a specific class and then doing
$(function() {
  $('#process').click(function () {
    var obj = [];
    $('.currency').each(function() {
       obj[$(this).attr('name')] = $(this).val();
    });
  });
});

Open in new window

full code here
<!doctype html>
<html>
<head>
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
  $('#process').click(function () {
    var obj = [];
    $('.currency').each(function() {
       obj[$(this).attr('name')] = $(this).val();
    });
  });
});
</script>
<style type="text/css">
</style>
</head>
<body>
Input here <input type="text" name="dollars" class="currency dollars"/> <input type="text" id="cents" name="cents" class="currency">
Input here <input type="text" name="dollars2" class="currency dollars"/> <input type="text" id="cents" name="cents2" class="currency">
<input type="button" id="process" value="Go" />
</body>
</html>

Open in new window

0
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
Steve KrileCommented:
Wonder if I could nudge you a little further back in your design.  Instead of handling this with jquery, why not look at a MVVM library like Knockout to do the heavy lifting.  This may seem a bit like magic when you first consider it, but it's really awesome.  The basic idea behind Knockout is to keep your view and your model as two separate things.  Take a look at my sample and we'll go from there.


<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html" />
<meta name="author" content="Evan Cutler" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-2.1.0.js"></script>
<title>Knockout Sample</title>
    
    <style type="text/css">
        body {font-family:Arial;}
        
    </style>
    <script type="text/javascript">
        var sampleJSONData = '[{"color": "Red", "size": "Large"}, {"color": "Blue", "size": "Large"}, {"color": "Pink", "size": "Medium"}]';

       
        //knockout uses a single object to hold all the model elements
        var pageModel = {};
        var modelData = ko.observableArray($.parseJSON(sampleJSONData));

        pageModel.saveData = ko.observable("No data selected");
        pageModel.save = function (data) {
            pageModel.saveData("You would be saving:<br/>" + ko.toJSON(data));
        };



        $(document).ready(function () {
            //wait until the page loads and apply the binding.
            ko.applyBindings(pageModel);
        });
        
    </script>
    
</head>

<body>


    <h1>Data Template</h1>
    <table>
        <thead>
            <tr>
                <th>Color</th>
                <th>Size</th>
                <th></th>
            </tr>
        </thead>
        <tbody data-bind="foreach: modelData">
            <tr>
                <td data-bind="text:color"></td>
                <td data-bind="text:size"></td>
                <td><a href="#" data-bind="click: $root.save">Save Data</a></td>
            </tr>
        </tbody>
    </table>
    <p>&nbsp;</p>
    <span data-bind="html: saveData" style="margin:10px;padding:10px;background:#ffc;border:solid 1px #ccc;display:inline-block;"></span>

    
</body>
</html>

Open in new window


Notice how you have JSON going in to your model and JSON coming out of your model.  No parsing required.
0
 
canuckconsultingAuthor Commented:
I went with my current approach and is working great.  Thanks!

Next project I am going to use MVVM library; it looks fantastic!

Thanks guys!
0
 
Steve KrileCommented:
FWIW, I've "injected" knockout pages in to my existing solutions without trouble.  It's nice and portable.
0
 
canuckconsultingAuthor Commented:
Good to know...I'm keen to get started with this but was reluctant to embark on another learning curve so close to my due date.  Thanks again.

Scott
0
 
Steve KrileCommented:
Yeah, knockout does require an investment at the beginning to get your feet wet.  I'd say I spent 20 hours just reading, playing, and getting to know it before I was able to use it.  I've been programming with it now for nearly a year so I'm quite proficient....but it's not immediately obvious just how powerful it is.

I remember having the sense that it was a good idea but not quite grasping how deep the rabbit hole was.  Now my applications are almost completely service-based - where I do everything through JSON posts to the server.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 3
  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now