0

I try to change value by default with a calcul : value by default * quantity / 100. In my script something does not work because nothing happened, I can't find what! (jQuery is very new for me...)

$(function () {
    $("#calcul").click(function (e) {
      e.preventDefault();
      var valeur = parseFloat($("#valquantite").text() );

      $("#nutrition > tbody > tr").each(function () {
        var valeurOrigin = parseFloat($(this).find("td").eq(1).text().replace(",", "."));
        var newValeur;
        if ($.isNumeric(valeurOrigin) === true) {
          newValeur = valeurOrigin*valeur/100;
          newValeur = Math.ceil(newValeur*1000)/1000;
        } else {
          newValeur = $(this).find("td").eq(1).text();
        }

        $(this).find("td").eq(2).html(newValeur);
      });
    });
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="overflow-x:scroll;;" name="formu">
<table class="table table-striped" id="nutrition" >
  <thead>
    <tr>
      <th>Aliments</th>
      <th id="qty">Poids</th>
      <th class="generaux">Energie kJ</th>
      <th class="generaux">Energie kcal</th>
    </thead>
      <tbody class="text-primary" id="">
      <tr><td>Pain au lait, préemballé:</td><td id="valquantite"><strong>35gr</strong></td>
        <td class="generaux" name="">1510</td>
        <td class="generaux">358</td>  
      </tr>
      <tr><td>Total</td>
        <td><strong>50gr</strong></td>
      </tr>
      </tbody>
    </table>
    <input class="btn btn-primary" type="button" value="Calculer" id="calcul" />

What i try to do is that the first column after the name retrieves the quantities from a table (different for each row), then I retrieve the values ​​by default columns energie_kj, energie_kcal, proteines, etc .. from a table (there are 60 Columns !! they are already calculated by default, I do not need to do any conversion). Some cells contain text (example: nc, traces, <) that I want to display as text. Then I have to calculate the total of each column (ignoring cells that contain text). That's my problem! I posted another question for the same problem with a code in js that works almost but not completely ... here: Javascript problems with NaN Thanks in advance for your answers.

Community
  • 1
  • 1
ginette
  • 55
  • 1
  • 7
  • And where is the table with the id nutrition? Also, you can't get the val() of an element that is not a form element. Instead, use var valeur = parseInt($("#valquantite").text() ); – Snowmonkey May 15 '17 at 13:09
  • Thanks for your answer, i understand, i put my "nutrition" in tbody instead "table", i changed it, and replaced var valeur val() by text() (because it's not a form). But the problem is the calcul is not good : i have 35 in quantity, 1510 value by default, and the result of value by default * quantity / 100 is 12.25 ... it's not the good result..it should be 528.5 – ginette May 15 '17 at 13:34

2 Answers2

0

Hope this will help you. Replace your code with following : I've just parse your valeur variable and replaced > sign when calling .each function and applied Id=nutrition to table rather than tbody tag.

  $(function () {
    $("#calcul").click(function (e) {
      e.preventDefault();
      var valeur = parseInt($("#valquantite").text());

      $("#nutrition tbody tr").each(function () {
        var valeurOrigin = parseFloat($(this).find("td").eq(2).text().replace(",", "."));
        var newValeur;
        if ($.isNumeric(valeurOrigin) === true) {
          newValeur = valeurOrigin*valeur/100;
          newValeur = Math.ceil(newValeur*1000)/1000;
        } else {
          newValeur = $(this).find("td").eq(1).text();
        }

        $(this).find("td").eq(2).html(newValeur);
      });
    });
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="overflow-x:scroll;;" name="formu">
<table class="table table-striped" id="nutrition">
  <thead>
    <tr>
      <th>Aliments</th>
      <th id="qty">Poids</th>
      <th class="generaux">Energie kJ</th>
      <th class="generaux">Energie kcal</th>
    </thead>
      <tbody class="text-primary">
      <tr><td>Pain au lait, préemballé:</td><td id="valquantite"><strong>35gr</strong></td>
        <td class="generaux" name="">1510</td>
        <td class="generaux">358</td>  
      </tr>
      <tr><td>Total</td>
        <td><strong>50gr</strong></td>
      </tr>
      </tbody>
    </table>
    <input class="btn btn-primary" type="button" value="Calculer" id="calcul" />
  • 1
    Wouldn't this *Replace your code* be better with an explanation?! – cнŝdk May 15 '17 at 13:20
  • It's the exact changes I suggested in my above comment. Good to have as an answer, would be better if you clarified what you'd done. Problem is, the OP has said they're just starting out with jQuery -- take the time to answer the question. – Snowmonkey May 15 '17 at 13:23
  • Ok, I've done as per previous comment.Mentioned explanation of my done things in answer and next time I'll keep this thing in mind surely. – Khanjan Bhatt May 15 '17 at 13:25
  • Well, the advantage to using the greater-than sign in the selector is it's a direct child -- if there were a nested table, all of those tr elements would also be selected by yours. Not saying either approach is WRONG, but I don't think that's the problem, really. – Snowmonkey May 15 '17 at 13:30
  • First problem is parsing the valeur variable and the id nutrition is given to the tbody tag not to table itself. I think this was the problem. – Khanjan Bhatt May 15 '17 at 13:33
  • Thanks for your answers. But even if i parse the valeur variable and id nutrition in the table, now i have a result but it's wrong, while the calcul is good. Why ?? – ginette May 15 '17 at 14:15
  • About the calculs i think the problem could be in this line : var valeurOrigin = parseFloat($(this).find("td").eq(1).text() because of ("td").eq(1). ? but i'm too novice for the moment in jQuery to understand what i need to change... please someone could help me ? – ginette May 15 '17 at 15:52
  • If 12.5 calculated value is wrong value than what calculated value should be displayed there? – Khanjan Bhatt May 16 '17 at 05:57
  • it should be 528.5 for Energie kJ and 125.3 for Energie kcal. If i change ("td").eq(1). for ("td").eq(2). the result is good but only for Energie kJ, the other one is not calculated. It should calculate horizontally for each line... – ginette May 16 '17 at 08:58
0

The issue may be, we don't know exactly what it is you're trying to calculate or where the data comes from. The valQuantite to which you refer, does that change for each row? If so, why is it defined outside of the each function? If not, why does it refer to a value from the first row of the table?

Doing a little research, you seem to want to take the quantity column and use that along with the energie kJ column to calculate... something. I'd suggest using classes for the three columns, valquantite, energie-kj, and energie-kcal, which you can then use to manipulate the individual columns in a meaningful way. Using $(this).find("td").eq(2).text() is only as good as the coder -- what if the column layout changes? Instead, simply use $(this).find(".energie-kj").text() and you're good.

Now, having gotten to displaying the kj as you'd like (by taking the qty and multiplying it by the kj, then rounding), you can calculate the kCal by dividing that number by 4.1868 and rounding as you'd like.

But note, I've modified your code -- the quantity seems to change with each row, so I've moved valQuantite inside the each statement. Also, I can't stress enough, I've commented my code to the point of silliness. Doing so makes it far easier to track what each line of code is SUPPOSED to be doing, as well as what it's actually doing. And use your console, it is your debugging FRIEND! lol

$(function() {
  // When the button is clicked, calculate the values.
  $("#calcul").click(function(e) {
    // First, make sure the button doesn't submit...
    e.preventDefault();

    // Each row is handled individually, so 
    $("#nutrition > tbody > tr").each(function() {
      // First, get the qty for this row
      var valeur = parseFloat($(this).find(".valquantite").text());
      /****
       * Here is a case. We have hard-wired to use the 
       *  third column of the table for the original val,
       *  but we could also add a class for this col and
       *  reference that: $(this).find(".energie-kj");
       ****/
      var valeurOrigin = parseFloat($(this).find("td").eq(2).text().replace(",", "."));
      var energyKJ, energyKCal;
      // If the energie kJ value is numeric, we do the first
      if ($.isNumeric(valeurOrigin) === true) {
        // calculate some value from the energie kJ and qty,
        energyKJ = valeurOrigin * valeur / 100;
        // 1 kCal = 4.1868 kJ, so do the conversion
        energyKCal = (energyKJ/4.1868).toFixed(2);
        energyKJ = energyKJ.toFixed(2);
      } else {
        // If the energie kJ value is NOT numeric, we simply
        //   set the displayed value to this
        newValeur = $(this).find("td").eq(2).text();
      }
      $(this).find(".energie-kj").text(energyKJ);
      $(this).find(".energie-kcal").text(energyKCal);
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="overflow-x:scroll;;" name="formu">
  <table class="table table-striped" id="nutrition">
    <thead>
      <tr>
        <th>Aliments</th>
        <th id="qty">Poids</th>
        <th class="generaux">Energie kJ</th>
        <th class="generaux">Energie kcal</th>
    </thead>
    <tbody class="text-primary" id="">
      <tr>
        <td>Pain au lait, préemballé:</td>
        <td class="valquantite"><strong>35gr</strong></td>
        <td class="generaux energie-kj" name="">1510</td>
        <td class="generaux energie-kcal">358</td>
      </tr>
      <tr>
        <td>Some other thing...:</td>
        <td class="valquantite"><strong>45gr</strong></td>
        <td class="generaux energie-kj" name="">1510</td>
        <td class="generaux energie-kcal">358</td>
      </tr>      <tr>
        <td>Total</td>
        <td><strong>50gr</strong></td>
      </tr>
    </tbody>
  </table>
  <input class="btn btn-primary" type="button" value="Calculer" id="calcul" />
Snowmonkey
  • 3,716
  • 1
  • 16
  • 16
  • First of all thank you very much for all these explanations, commenting on the code helps me a lot to understand my mistakes. To be honest I am a beginner in js and jQuery, I try to understand little by little and I retrieved this code from another page that had only 2 active columns (one that retrieves the default values ​​and the other The calculated values). I updated my post to explain better what I want to do. If you still have a little time to help me... :)) – ginette May 19 '17 at 09:18