最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using jquery to get per row totals and grand total of table - Stack Overflow

programmeradmin2浏览0评论

So the short version of this is: Can I traverse only the elements within the matched element of the selectors before the each()? Or is there a simpler way of getting what I want without an each() loop?


I thought this would be much easier, which makes me think I'm just missing some fundamental principle of element traversing with jquery.

So here's the scenario:

I have a table (and it is appropriate in this case), where each cell has a text input. The last input is read-only and is supposed to be the total sum of the other values entered on that row. I have a really messy js script for finding both the totals of each row and then the grand total of each row total.

Here's the basic HTML:

<table>
<thead>
<tr><th>Col 1</th><th>Col 2</th><th>Col 3</th><th>Total</th></tr>
</thead>
<tbody>
<tr id="row1"><td><input type="text" /></td><td><input type="text" /></td><td><input type="text" /></td><td class="total"><input type="text" readonly="readonly" /></td></tr>
<tr id="row2"><td><input type="text" /></td><td><input type="text" /></td><td><input type="text" /></td><td class="total"><input type="text" readonly="readonly" /></td></tr>
<tr id="row3"><td><input type="text" /></td><td><input type="text" /></td><td><input type="text" /></td><td class="total"><input type="text" readonly="readonly" /></td></tr>
</tbody>
</table>

The javascript will validate that the data entered is numerical, just to be clear.

So I have a event listener for each input for onchange that updates the total when the user enters data and moves to the next cell/input. Then I have a function called updateTotal that currently uses for loops to loop through each row and within that loop, each cell, and finally sets the input in the total cell to sum.

Quick note: I have included the code below to show that I'm not just looking for a hand out and to demonstrate the basic logic of what I have in mind. Please feel free to skim or skip this part. It works and doesn't need any debugging or critique.

This is what that looks like:

function updateTotal() {
    table = document.getElementsByTagName("tbody")[0];
    allrows = table.getElementsByTagName("tr");
    grandtotal = document.getElementById("grand");
    grandtotal.value = "";

    for (i = 0; i < allrows.length; i++) {
        row_cells = allrows[i].getElementsByTagName("input");
        row_total = allrows[i].getElementsByTagName("input")[allrows.length - 2];
        row_total.value = "";

        for (ii = 0; ii < row_cells.length - 1; ii++) {
            row_total.value = Number(row_total.value) + Number(row_cells[i][ii].value);
            grandtotal.value = Number(grandtotal.value) + Number(row_cells[i][ii].value);
        }
    }
}

Now I am trying to re-write the above with jquery syntax, but I'm getting stuck. I thought the best way to go would be to use each() loops along the lines of:

function findTotals() {
$("tbody tr").each(function() {
    row_total = 0; 
    $($(this) + " td:not(.total) input:text").each(function() {
        row_total += Number($(this).val());
        }); 
    $($(this) + " .total :input:text").val(row_total);
});

}

But using $(this) doesn't seem to work in the way I thought. I read up and saw that the use of $(this) in an each loop points to each matched element, which is what I expected, but I don't get how I can traverse through that element in the each() function. The above also leaves out the grand_total bit, because I was having even less luck with getting the grand total variable to work. I tried the following just to get the row_totals:

 $($(this).attr("id") + " td:not(.total) input:text").each(function() {

with some success, but then managed to break it when I tried adding on to it. I wouldn't think I'd need each row to have an id to make this work, since the each part should point to the row I have in mind.


So the short version of this is: Can I use the each loop to traverse only the elements within the matches, and if so, what is the correct syntax? Or is there a simpler way of getting what I want without an each loop?

Oh, one last thought...

Is it possible to get the numerical sum (as opposed to one long string) of all matched elements with jquery? I'll research this more myself, but if anyone knows, it would make some of this much easier.

So the short version of this is: Can I traverse only the elements within the matched element of the selectors before the each()? Or is there a simpler way of getting what I want without an each() loop?


I thought this would be much easier, which makes me think I'm just missing some fundamental principle of element traversing with jquery.

So here's the scenario:

I have a table (and it is appropriate in this case), where each cell has a text input. The last input is read-only and is supposed to be the total sum of the other values entered on that row. I have a really messy js script for finding both the totals of each row and then the grand total of each row total.

Here's the basic HTML:

<table>
<thead>
<tr><th>Col 1</th><th>Col 2</th><th>Col 3</th><th>Total</th></tr>
</thead>
<tbody>
<tr id="row1"><td><input type="text" /></td><td><input type="text" /></td><td><input type="text" /></td><td class="total"><input type="text" readonly="readonly" /></td></tr>
<tr id="row2"><td><input type="text" /></td><td><input type="text" /></td><td><input type="text" /></td><td class="total"><input type="text" readonly="readonly" /></td></tr>
<tr id="row3"><td><input type="text" /></td><td><input type="text" /></td><td><input type="text" /></td><td class="total"><input type="text" readonly="readonly" /></td></tr>
</tbody>
</table>

The javascript will validate that the data entered is numerical, just to be clear.

So I have a event listener for each input for onchange that updates the total when the user enters data and moves to the next cell/input. Then I have a function called updateTotal that currently uses for loops to loop through each row and within that loop, each cell, and finally sets the input in the total cell to sum.

Quick note: I have included the code below to show that I'm not just looking for a hand out and to demonstrate the basic logic of what I have in mind. Please feel free to skim or skip this part. It works and doesn't need any debugging or critique.

This is what that looks like:

function updateTotal() {
    table = document.getElementsByTagName("tbody")[0];
    allrows = table.getElementsByTagName("tr");
    grandtotal = document.getElementById("grand");
    grandtotal.value = "";

    for (i = 0; i < allrows.length; i++) {
        row_cells = allrows[i].getElementsByTagName("input");
        row_total = allrows[i].getElementsByTagName("input")[allrows.length - 2];
        row_total.value = "";

        for (ii = 0; ii < row_cells.length - 1; ii++) {
            row_total.value = Number(row_total.value) + Number(row_cells[i][ii].value);
            grandtotal.value = Number(grandtotal.value) + Number(row_cells[i][ii].value);
        }
    }
}

Now I am trying to re-write the above with jquery syntax, but I'm getting stuck. I thought the best way to go would be to use each() loops along the lines of:

function findTotals() {
$("tbody tr").each(function() {
    row_total = 0; 
    $($(this) + " td:not(.total) input:text").each(function() {
        row_total += Number($(this).val());
        }); 
    $($(this) + " .total :input:text").val(row_total);
});

}

But using $(this) doesn't seem to work in the way I thought. I read up and saw that the use of $(this) in an each loop points to each matched element, which is what I expected, but I don't get how I can traverse through that element in the each() function. The above also leaves out the grand_total bit, because I was having even less luck with getting the grand total variable to work. I tried the following just to get the row_totals:

 $($(this).attr("id") + " td:not(.total) input:text").each(function() {

with some success, but then managed to break it when I tried adding on to it. I wouldn't think I'd need each row to have an id to make this work, since the each part should point to the row I have in mind.


So the short version of this is: Can I use the each loop to traverse only the elements within the matches, and if so, what is the correct syntax? Or is there a simpler way of getting what I want without an each loop?

Oh, one last thought...

Is it possible to get the numerical sum (as opposed to one long string) of all matched elements with jquery? I'll research this more myself, but if anyone knows, it would make some of this much easier.

Share Improve this question asked Sep 1, 2009 at 1:05 AnthonyAnthony 37.1k26 gold badges103 silver badges167 bronze badges 1
  • To those about to torch me for a repeat question: 1) I can't find any documentation on the sum() method, 2) I would like to know in general how to traverse an element with an each loop without needing an ID or class of some sort. – Anthony Commented Sep 1, 2009 at 1:06
Add a comment  | 

2 Answers 2

Reset to default 16

You are trying to set your context incorrectly try this:

function findTotals() {
    $("tbody tr").each(function() {
        row_total = 0; 
        $("td:not(.total) input:text",this).each(function() {
           row_total += Number($(this).val());
        }); 
        $(".total :input:text",this).val(row_total);
    });

}

For more information about the context check out the jquery docs: http://docs.jquery.com/Core/jQuery#expressioncontext

There can be two parameters for a selector. The second parameter is the context htat that the search is to take place in. Try something like the following: $('#tableID tbody tr).each(function(){ //now this is a table row, so just search for all textboxes in that row, possibly with a css class called sum or by some other attribute $('input[type=text]',this).each(function(){ //selects all textbosxes in the row. $(this).val() gets value of textbox, etc. }); //now outside this function you would have the total //add it to a hidden field or global variable to get row totals, etc. });

发布评论

评论列表(0)

  1. 暂无评论