1

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>
4
  • 1
    You have jQuery code and not javascript. Commented Jun 2, 2019 at 7:39
  • 1
    if you are strong in php, just ommit the ; and the $ and you are strong in js too :P Commented Jun 2, 2019 at 7:47
  • I can't see` input button` within p tag ` $('p input[type="button"]')`. You want total to be displayed as new row is created? I am not really clear about the question. But, when new row is added the price and count input fields are empty. Commented Jun 2, 2019 at 7:50
  • @johnSmith I am learning that; few things throw me for a loop. Commented Jun 4, 2019 at 6:38

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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)

3 Comments

Doesn't $( this ).val() return a string in this case? So your sum will be a string?
Not sure if it does this, but I've added parseInt just incase. Thanks :)
Reflected the above. Smart Man.
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.