Search code examples
jqueryformsinputsubtotal

Calculating subtotals using jquery


How do I go about fetching from (or writing to) input fields relative to $(this) in a form?

I wish to loop through all input fields "antal" and calculate subtotals based on "antal" multiplied by the price relative to "antal" and store the calculated price in a subtotal input field relative to "antal".

A full pen here http://codepen.io/Ktraving/pen/RKRGQG

$("input").change(function(){
    var subtot=0;
    var total=0;

    $("input[name=antal]").each(function(){                                             
       subtot = subtot + (parseInt($(this).val()) * $("input[name=pris]").val());
        $("input[name=subpris]").val(subtot);                                           
    });

    /* Totalling the subtotals */

    $("input[name=subpris]").each(function(){
        total = total + parseInt($(this).val());
    });

    $("input[name=totpris]").val(total);
});

Solution

  • You could use closest() to go up to the parent then find the related input with name pris/subpris :

    $(this).closest('div').find("input[name=pris]").val();
    

    NOTE : No need for each() just calculate the sub total of the current input antal, also I suggest the use of input instead of change when you track the field.

    Hope this helps.

    $(document).ready(function(){
      $("input[name='antal']").on('input', function(){
        var subtot=0;
        var total=0;
        var parent = $(this).closest('.maling_rekke');
        var pris = parent.find("input[name=pris]").val();
    
        subtot += parseInt($(this).val()) * pris;
        parent.find("input[name=subpris]").val(subtot);
    
        $("input[name=subpris]").each(function(){				
          total = total + parseInt($(this).val());			
        });
    
        $("input[name=totpris]").val(total);					
      });
    });
    /* Overordnet styling */
    * 
    {
      box-sizing:border-box;
      margin:0vw;
      padding:0vw;
    }
    
    fieldset
    {
      margin-bottom:20px;
      border-color:red;
      border-width:5px;
      background:#eee;
    }
    
    legend
    {
      margin-left:15px;
      padding:5px;
      font-size:20px;
      font-weight:bold;
    }
    
    /* Overordnet ramme, der på sigt kan benytte flexbox for at gøre formularen responsiv */
    
    .flex_ramme 
    {
      width: 500px;
      display: -webkit-flex;
      display: flex;
      flex-direction:column;
      background-color: white;
      margin:30px 30px 30px 30px;
    }
    
    
    /* Styling af formular og felter til formularen */
    
    
    .maling_rekke
    {
      padding:10px 0px 10px 10px;
      clear:both;
    }
    
    .maling_felt
    {
      padding:5px;
      max-width:80vw;
    }
    
    .maling_billede
    {
      height:100px;
    }
    
    .maling_ramme
    {
      float:left;
      min-width:130px;
      max-width:30vw;
      height:200px;
      padding-right:10px;
    }
    
    
    
    
    /* Styling af afsluttende knapper */
    
    .knapper
    {
      float:right;
    }
    
    #knap_nulstil
    {
      margin-right:20px;
      background-color: #CC3230; /* Green */
      border: none;
      color: white;
      padding: 15px 32px;
      text-align: center;
      text-decoration: none;
      display: inline-block;
      font-size: 16px;	
    }
    
    #knap_nulstil:hover
    {
      transition: background-color 0.8s ease;
      background-color:#ff3230;	
    }
    
    
    #knap_bestil
    {
      background-color: #4CAF50; 
      border: none;
      color: white;
      padding: 15px 32px;
      text-align: center;
      text-decoration: none;
      display: inline-block;
      font-size: 16px;
    }
    
    #knap_bestil:hover
    {
      transition: background-color 0.8s ease;
      background-color: #4CDF50; /* Green */
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div class="flex_ramme">
    
      <form action="send_bestilling.php" method="post">
    
        <fieldset>
    
          <legend>Bestilling af maling</legend>
    
          <div class="maling_rekke">
            <div class="maling_ramme">
              <img class="maling_billede maling_felt" src="spand.jpg" alt="Maling type A">
            </div>
            <p class="maling_type maling_felt">Sigma S2U Satin - slidstærk</p>
            <p class="maling_pris">100 kr.</p><input type="hidden" name="pris" value="100">
            <p class="maling_felt">Antal:</p> <input class="maling_input maling_felt" type="text" name="antal" value="0"><br>
            <p class="maling_felt">Subtotal (inkl. moms):</p> <input class="maling_sub maling_felt" type="text" name="subpris" value="0" readonly>
          </div>
    
          <div class="maling_rekke">
            <div class="maling_ramme">
              <img class="maling_billede maling_felt" src="spand2.jpg" alt="Maling type A">
            </div>
            <p class="maling_type maling_felt">Yunik Træmaling</p>
            <p class="maling_pris">200 kr.</p><input type="hidden" name="pris" value="200">			    	
            <p class="maling_felt">Antal:</p> <input class="maling_input maling_felt" type="text" name="antal" value="0"><br>
            <p class="maling_felt">Subtotal (inkl. moms):</p> <input class="maling_sub maling_felt" type="text" name="subpris" value="0" readonly>
          </div>
    
          <div class="maling_rekke">
            <div class="maling_ramme">
              <img class="maling_billede maling_felt" src="spand3.jpg" alt="Maling type A">
            </div>
            <p class="maling_type maling_felt">Yunik Radiatormaling</p>
            <p class="maling_pris">300 kr.</p><input type="hidden" name="pris" value="300">			    	
            <p class="maling_felt">Antal:</p> <input class="maling_input maling_felt" type="text" name="antal" value="0"><br>
            <p class="maling_felt">Subtotal (inkl. moms):</p> <input class="maling_sub maling_felt" type="text" name="subpris" value="10" readonly>
          </div>
    
        </fieldset>
    
        <fieldset>
    
          <legend>Godkendt bestilling</legend>
    
          <div class="maling_rekke">
            Total (inkl. moms): <input class="maling_totalt maling_felt" type="text" name="totpris" value="0" readonly> DKK.</br>
          <input class="maling_felt" type="checkbox" name="godkend" value="Bike">Jeg godkender hermed bestillingen<br>   	
          </div>
    
        </fieldset>
    
      <div class="knapper">
    
        <input id="knap_nulstil" type="reset" value="Nulstil">
        <input id="knap_bestil" type="submit" value="Send bestilling">
    
      </div>
    
      </form>
    
    </div> <!-- Slut anden flexramme -->