javascript, sum of Label

Asked

Viewed 203 times

3

I have in a table, several label ex:

<td style="width:10%"><label id="PrecoProd_3" class="negrito">R$ 1.502,25</label></td>

There are several lines with this type, changing only id

I’d like to put it down at a certain place on page one <label></label> with the total sum

I could do jquery, pure javascript, anyway, but I haven’t been able to isolate the fields, since I don’t know the ID (can have several lines, so I can’t refer to the label id (I believe)

tried to do so

 function id(el) {
        return document.getElementById(el);
    }
    function somaLabel() {
        //Produtos - é o ID da tabela,
        var inputs = id('Produtos').getElementsByTagName('label');

        var soma = 0;
        for (var i = 0; i < inputs.length; i++) {
            soma += parseInt(inputs[i].value);
        }
        alert(soma);
        //id('resultado').value = soma;
    }

Alert is giving NAN Alert just for testing, because I tried to do on the final label. Example of the application:

http://fiddle.jshell.net/dorathoto/3xDgX/

  • Your values have commas sometimes and points in others. You can correct these values or you have to work with them as they are?

  • I think to standardize...I just need to correct the other js, but yes

1 answer

4


The error is on the line

sum += parseint(inputs[i]. value);

The element label does not have the attribute value, the way you’re hoping.

For that, you need to take the text of label, that by DOM, is your first child.

Thus:

soma += parseFloat(inputs[i].firstChild.nodeValue.substr(3).replace(/\./g, "").replace(/,/g, ".")));
  • The substr is to skip the beginning of your string "R$ "
  • I used parseFloat because of the decimal places
  • The replace are to remove the thousand separator (".") and then replace the decimal separator "," for ".", so that the parseFloat can function properly

Also, after reading the whole fiddle, there was an error in the conversion to currency function: missing replace the "." generated by the method toFixed for ",", in addition to correcting the regular expression that adds the thousand separator. The complete fiddle is here.

The final code, already corrected, of the function in question is shown below:

function formatDinheiro(n, currency) {
    //às vezes n vem como NaN, quando o usuário deixa o campo em branco
    if (isNaN(n))
        n = 0;
    //converte n para string com 2 casas decimais
    var x = (currency + " " + n.toFixed(2).replace(/\./g, ",")).split(","),
        x1 = x[0],
        x2 = ((x.length > 1) ? "," + x[1] : ""),
        rgx = /(\d+)(\d{3})/;
    //acrescenta um separador de milhar a cada 3 dígitos
    while (rgx.test(x1))
        x1 = x1.replace(rgx, '$1' + '.' + '$2');
    return x1 + x2;
}

Another mistake is that by doing:

var inputs = id('Products'). getelementsbytagname('label');

The label with the subtotal is also returned in the array, so its value entered the sum again. The corrected code of this function is shown below:

function somaLabelProduto() {
    var inputs = id("Produto").getElementsByTagName('label');

    var soma = 0;
    for (var i = 0; i < inputs.length; i++) {
        if (inputs[i].id != "sub_total_0")
            soma += parseFloat(inputs[i].firstChild.nodeValue.substr(3).replace(/\./g, "").replace(/,/g, "."));
    }

    document.getElementById('sub_total_0').innerHTML = formatDinheiro(soma, "R$");
}
  • I made your change but it didn’t work, I don’t think I understood. http://fiddle.jshell.net/dorathoto/3xDgX/1/

  • Hi @Dorathoto! I edited the answer. See the last potno I added at the end...

  • Hi again, @Dorathoto! Your fiddle example doesn’t work because there are more errors, besides the one you mentioned...

  • 1

    Okay, @Dorathoto! I tidied up your code, take a look at the fiddle: http://fiddle.jshell.net/3xDgX/2/ The main error was where the function was soma was being called.

  • showwwww, now yes.. perfect, magical.. rs http://fiddle.jshell.net/dorathoto/3xDgX/4/ , some things, from NAN, but it looks good.

  • @Dorathoto What is resulting in NaN may be some conversion problem (wrong string), blank string, or some undefined. However, I noticed in that new fiddle of yours that the function somaLabel went back inside MudaLabeL. Is that right? Another thing, is that its function SomaTotal is wrong: she is concatenating strings (missing put parseFloat at each term document.getEle... nodeValue.substr(3) before adding up)

  • I switched inside, because when changing the price it must be recalculated again, as I did not know how to make one for each table, I doubled the Function that added.. Mudallabela and Mudalabelb :( http://fiddle.jshell.net/dorathoto/3xDgX/5/

  • even on your link it does not add labels, it just concatenates.. I tried to change and it still hasn’t worked http://fiddle.jshell.net/dorathoto/3xDgX/6/

  • @Dorathoto I’m on chat...

  • http://chat.stackexchange.com/rooms/14607/discussion-between-dorathoto-and-carlosrafaelgn

Show 6 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.