LeviZoesch
LeviZoesch

Reputation: 1621

Javascript/Jquery sum input fields as user enters

I would like to be blunt; I am weak with Javascript/Jquery. I am learning :) I am very strong in PHP.

I have a table that shows a user a single line item that they can enter information into. This form is a "change order". I am having difficulties understanding what I need to do to get the input fields "Count" and "Price" to sum by the example in the Total Category. I would also need to have this summation occur during each new row inserted.

This page will generate a template'd PDF document containing the line items entered.

enter image description here

My Javascript code ive put together is;

    let count = 0;
    $('p input[type="button"]').click(function () {
        count += 1;
    })
    $('#myTable').on('click', 'input[type="button"]', function () {
        $(this).closest('tr').remove();
    })
    $('p input[type="button"]').click(function () {
        var varItem = 'item_' + count;
        var varCount = 'count_' + count;
        var varPrice = 'price_' + count;
        var varTotal = 'total_' + count;
        $('#myTable').append('' +
            '<tr>' +
                '<td>' +
                    '<input type="text" class="form-control" name="' + varItem + '"/>' +
                '</td>' +
                '<td>' +
                    '<input type="text" class="form-control" name="' + varCount + '"/>' +
                '</td>' +
                '<td>' +
                    '<input type="text" class="form-control" name="' + varPrice + '"/>' +
                '</td>' +
                '<td>' +
                    'Count * Price = Total' +
                '</td>' +
                '<td>' +
                    '<input type="button" class="btn btn-sm btn-danger" value="Delete" />' +
                '</td>' +
            '</tr>'
        )
    });

HTML

<table id="myTable" class="table table-hover table-striped width-full">
                                    <thead>
                                    <tr>
                                        <th>Item</th>
                                        <th>Count</th>
                                        <th>Price</th>
                                        <th>Total</th>
                                        <th>Action</th>
                                    </tr>
                                    </thead>
                                    <tbody>
                                        <tr>
                                            <td>
                                                <input type="text" class="form-control" name="item_0" />
                                            </td>
                                            <td>
                                                <input type="text" class="form-control" name="count_0" />
                                            </td>
                                            <td>
                                                <input type="text" class="form-control" name="price_0" />
                                            </td>
                                            <td>
                                                Count * Price = Total
                                            </td>
                                            <td>
                                                <input type="button" class="btn btn-sm btn-danger" value="Delete" />
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>

Upvotes: 1

Views: 231

Answers (3)

Chiến Ngh&#234;
Chiến Ngh&#234;

Reputation: 776

I made this codepen base on your code

$(document).ready(function() {
  let count = 0;
  $('p input[type="button"]').click(function() {
    count += 1;
  })
  $('#myTable').on('click', 'input[type="button"]', function() {
    $(this).closest('tr').remove();
  })
  $('p input[type="button"]').click(function() {
    var varItem = 'item_' + count;
    var varCount = 'count_' + count;
    var varPrice = 'price_' + count;
    var varTotal = 'total_' + count;
    $('#myTable').append('' +
      '<tr>' +
      '<td>' +
      '<input type="text" class="form-control" name="' + varItem + '"/>' +
      '</td>' +
      '<td>' +
      '<input type="text" class="form-control quantity" name="' + varCount + '"/>' +
      '</td>' +
      '<td>' +
      '<input type="text" class="form-control price" name="' + varPrice + '"/>' +
      '</td>' +
      '<td class="' + varTotal + '">' +
      'Count * Price = Total' +
      '</td>' +
      '<td>' +
      '<input type="button" class="btn btn-sm btn-danger" value="Delete" />' +
      '</td>' +
      '</tr>'
    )
  });

  $(document).on("change", ".quantity", function() {
    $quantity = $(this);
    $index = $quantity.attr('name').split('_')[1]
    $price = $('input[name="price_' + $index + '"]').val()
    $('.total_' + $index).text($price ? $price * $quantity.val() : 0)
    // alert($price);  // jQuery 1.7+
  });

  $(document).on("change", ".price", function() {
    $price = $(this);
    $index = $price.attr('name').split('_')[1]
    $quantity = $('input[name="count_' + $index + '"]').val()
    $('.total_' + $index).text($quantity ? $quantity * $price.val() : 0)
  });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p><input type='button' value='Add'></p>
<table id="myTable" class="table table-hover table-striped width-full">
  <thead>
    <tr>
      <th>Item</th>
      <th>Count</th>
      <th>Price</th>
      <th>Total</th>
      <th>Action</th>
    </tr>
  </thead>
  <tbody>

  </tbody>
</table>

The idea is to bind the event to quantity & price input fields whenever their values change, then update the total value at corresponding row index. In order to bind change events for dynamically added elements, please refer to JQuery's live() helper.

You will then see the cart working as following image

enter image description here

Upvotes: 2

random
random

Reputation: 7891

Apply the change event to price and count input. When both the values are present, change the text of total field with the val of price*count.

let count = 0;

$('p input[type="button"]').click(function () {
    count += 1;
})
$('#myTable').on('click', 'input[type="button"]', function () {
    $(this).closest('tr').remove();
})
$('p input[type="button"]').click(function () {
    var varItem = 'item_' + count;
    var varCount = 'count_' + count;
    var varPrice = 'price_' + count;
    var varTotal = 'total_' + count;
    $('#myTable').append('' +
        '<tr>' +
            '<td>' +
                '<input type="text" class="form-control" name="' + varItem + '"/>' +
            '</td>' +
            '<td>' +
                '<input type="text" class="form-control" name="' + varCount + '"/>' +
            '</td>' +
            '<td>' +
                '<input type="text" class="form-control" name="' + varPrice + '"/>' +
            '</td>' +
            '<td>' +
                'Count * Price = Total' +
            '</td>' +
            '<td>' +
                '<input type="button" class="btn btn-sm btn-danger" value="Delete" />' +
            '</td>' +
        '</tr>'
    );
    calculateTotal();
});

function calculateTotal() {
    $('input[name^="count"], input[name^="price"]').on('change', function() {
        const inputName = $(this).attr('name').split('_')[1];
        const count = +($(`input[name="count_${inputName}"]`).val());
        const price = +($(`input[name="price_${inputName}"]`).val());

        if(count && price) {
            const total = $(`input[name="price_${inputName}"]`).parent().next();
            $(total).text(count*price);
        }
    });
}

calculateTotal();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTable" class="table table-hover table-striped width-full">
  <thead>
    <tr>
      <th>Item</th>
      <th>Count</th>
      <th>Price</th>
      <th>Total</th>
      <th>Action</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>
        <input type="text" class="form-control" name="item_0" />
      </td>
      <td>
        <input type="text" class="form-control" name="count_0" />
      </td>
      <td>
        <input type="text" class="form-control" name="price_0" />
      </td>
      <td>
        Count * Price = Total
      </td>
      <td>
        <input type="button" class="btn btn-sm btn-danger" value="Delete" />
      </td>
    </tr>
  </tbody>
</table>
<p>
  <input type="button" value="Add Row">
</p>

Upvotes: 0

Agoose Banwatti
Agoose Banwatti

Reputation: 450

Add a class name to your price inputs (ive added priceInput)

<input type="text" class="form-control priceInput" name="' + varPrice + '"/>

then find the sum with

sum = 0
$( ".printInput" ).each(function( index ) {
  sum+= Number($( this ).val())
});
console.log("The sum is : " + sum)

Upvotes: 1

Related Questions