[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Traverse table using JQuery / JavaScript concatenating input values

Posted on 2012-09-10
8
Medium Priority
?
773 Views
Last Modified: 2012-09-21
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
Comment
Question by:canuckconsulting
  • 3
  • 3
  • 2
8 Comments
 
LVL 60

Expert Comment

by:Julian Hansen
ID: 38382149
Why not put the table inside a form element and then use JQuery serialize to get the data.
0
 

Author Comment

by:canuckconsulting
ID: 38382438
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
 
LVL 60

Accepted Solution

by:
Julian Hansen earned 1200 total points
ID: 38382459
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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 16

Assisted Solution

by:Steve Krile
Steve Krile earned 800 total points
ID: 38382721
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
 

Author Closing Comment

by:canuckconsulting
ID: 38421339
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
 
LVL 16

Expert Comment

by:Steve Krile
ID: 38421345
FWIW, I've "injected" knockout pages in to my existing solutions without trouble.  It's nice and portable.
0
 

Author Comment

by:canuckconsulting
ID: 38421372
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
 
LVL 16

Expert Comment

by:Steve Krile
ID: 38421384
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

Featured Post

Prep for the ITIL® Foundation Certification Exam

December’s Course of the Month is now available! Enroll to learn ITIL® Foundation best practices for delivering IT services effectively and efficiently.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

How to build a simple, quick and effective accordion menu using just 15 lines of jQuery and 2 css classes
Originally, this post was published on Monitis Blog, you can check it here . In business circles, we sometimes hear that today is the “age of the customer.” And so it is. Thanks to the enormous advances over the past few years in consumer techno…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses
Course of the Month18 days, 14 hours left to enroll

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question