0

I create my personal project, and I called this system as ordering system I used laravel for this and the front end javascript and jquery.

I have question

Question:

  1. I used the append function of jquery to transfer value to other side. so i append input type number which the value automatically equal to 1

The question if I increment the value of input type number how the price double if i increase the value of number?

Example of my output

My output

My Front end Codes:

        var tbody = $('#myTable').children('tbody');

        //Then if no tbody just select your table 
        var table = tbody.length ? tbody : $('#myTable');



        //my logic to increment quantity but not working.


        $("#qty_change").bind('keyup mouseup', function () {
            alert("changed");            
        });


        //function for getting the data from search product by clicking to the table row

        $("tr#productClicked").click(function () {

            //to get the price in tr
            var price = $(this).closest("tr").find(".menu_price").text();

            //to get the menu in tr
            var menu_name = $(this).closest("tr").find(".menu_name").text();

            //row count
            var rowCount = $('table#myTable tr:last').index() + 1;

            //append input to quantity the value is 1
            var input = '<input type="number" name="qty_number" class="form-control" value="1" id="qty_change" />';



            //Item must be editable
            var contenteditable = 'contenteditable=true';



            table.append('<tr><td>'+rowCount+'</td><td class="total">'+input+'</td><td '+contenteditable+'>'+menu_name+'</td><td>'+price+'</td><td>'+price+'</td></tr>');


        });

Html Table:

 <table class="table table-hover" id="myTable">
<thead>
<tr style="font-size: 14px; ">
    <th scope="col">#</th>
    <th scope="col">Qty</th>
    <th scope="col">Item</th>
    <th scope="col" style="text-align: right">Cost</th>
    <th scope="col" style="text-align: right">Total</th>
</tr>
</thead>
<tbody style="font-size:14px;">                 
<tr>
    {{-- <td>1</td>
    <td>x 2</td>
    <td contenteditable='true'>Feast Chicken</td>
    <td align="right">$10.00</td>
    <td align="right">$20.00</td> --}}
</tr>
</tbody>

</table>

New update:

$('.amount > input[type="number"]').on('input', updateTotal);

        function updateTotal(e){
          var value = e.target.value;

          // Don't do anything if value is not valid
          // else you will see NaN in result.
          if (!value || value < 0)
            return;

          var $parentRow = $(e.target).parent().parent();
          var $siblingTotal = $parentRow.find('.total');
          var $siblingCost = $parentRow.find('.cost');

          var cost = $siblingCost.text();

          // parseInt and parseFloat because
          // `value` and `cost` are strings.
          value = parseInt(value);
          cost = parseFloat(cost);

          $siblingTotal.text(value * cost);
        }




$("tr#productClicked").click(function () {

            swal({
              title: "Are you sure?",
              text: "Once you will add it will automatically send to the cart",
              icon: "warning",
              buttons: true,
              dangerMode: true,
            })
            .then((willDelete) => {
              if (willDelete) {

                    swal("Poof! Your imaginary file has been deleted!", {
                      icon: "success",
                    });

                    swal("Menu Added", "You clicked the button!", "success");

                    //to get the price in tr
                    var price = $(this).closest("tr").find(".menu_price").text();

                    //to get the menu in tr
                    var menu_name = $(this).closest("tr").find(".menu_name").text();

                    //row count
                    var rowCount = $('table#myTable tr:last').index() + 1;

                    //append input to quantity the value is 1
                    var input = '<input type="number" value="1">';



                    //Item must be editable
                    var contenteditable = 'contenteditable=true';



                    table.append('<tr><td>'+rowCount+'</td><td class="amount">'+input+'</td><td '+contenteditable+'>'+menu_name+'</td><td class="cost">'+price+'</td><td class="total">'+price+'</td></tr>');


              } else {
                swal("Cancelled");
              }
            });

        });
DevGe
  • 1,381
  • 4
  • 35
  • 66

1 Answers1

2

Listen for "input" event using jQuery's .on.

(Please note that "input" event has nothing to do with jQuery, it's a native JavaScript thing.)

This is a sample code, because the code you provided is not complete. But you should be able to get the concept:


Usual code sample

$('.amount > input[type="number"]').on('input', updateTotal);

function updateTotal(e){
  var amount = parseInt(e.target.value);
  
  if (!amount || amount < 0)
    return;
    
  var $parentRow = $(e.target).parent().parent();
  var cost = parseFloat($parentRow.find('.cost').text());
  var total = (cost * amount).toFixed(2);
  
  $parentRow.find('.total').text(total);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table>
  <thead>
    <tr>
      <th>Input</th>
      <th>Cost per item</th>
      <th>Total</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="amount"><input type="number" value="1"></td>
      <td class="cost">27</td>
      <td class="total">27</td>
    </tr>
    <tr>
      <td class="amount"><input type="number" value="1"></td>
      <td class="cost">14.50</td>
      <td class="total">14.50</td>
    </tr>
  </tbody>
</table>

For the sake of understanding

// Get all inputs with type="number"
// that is a child of <td class="amount">.
var $amountInput = $('td.amount > input[type="number"]');

// Attach "input" event listener to the input fields
// so that we know when the value changes and handle the changes.
// In this case, the event handler is the function "updateTotal".
$amountInput.on('input', updateTotal);


function updateTotal(e){
  // Get the `input` element that triggers this event.
  var $thisInput = $(e.target);

  // Get the value of $thisInput
  var amount = $thisInput.val();
  
  // The `value` is a string,
  // so we need `parseInt` to make it a number.
  // Use `parseInt` because quantity can't have decimals.
  amount = parseInt(amount);

  // Don't do anything if value is not valid
  // else you will see NaN in result.
  if (!amount || amount < 0)
    return;

  // Get the parent <tr> of this input field
  var $parentRow = $thisInput.parent().parent();
  
  // Find the <td class="total"> element
  var $siblingTotal = $parentRow.find('.total');
  
  // Find the <td class="cost"> element
  var $siblingCost = $parentRow.find('.cost');

  // Get the cost from <td class="cost"> element
  var cost = $siblingCost.text();

  // The "cost" is a string,
  // so we need `parseFloat` to make it a number.
  // Use `parseFloat` because cost can have decimals.
  cost = parseFloat(cost);

  // Calculate the total cost
  var total = amount * cost;
  
  // .toFixed(2) to force 2 decimal places
  total = total.toFixed(2);
  
  // Update the total cost into <td class="total"> element
  $siblingTotal.text(total);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table>
  <thead>
    <tr>
      <th>Input</th>
      <th>Cost per item</th>
      <th>Total</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="amount"><input type="number" value="1"></td>
      <td class="cost">27</td>
      <td class="total">27</td>
    </tr>
    <tr>
      <td class="amount"><input type="number" value="1"></td>
      <td class="cost">14.50</td>
      <td class="total">14.50</td>
    </tr>
  </tbody>
</table>

Note

If you still have difficulties understanding, you might want to read:

  1. Why prefix "$" sign in only some variable names? (Generally called the Hungarian Notation)
  2. What is td.amount > input[type="number"]?
  3. What is jQuery's .on()?
  4. What is e.target?
  5. What is jQuery's .val()?
  6. What is parseInt()?
  7. What is parseFloat()?
  8. What does !value mean?
  9. Why do you return nothing?
  10. What is jQuery's .parent()?
  11. What is jQuery's .find()?
  12. What is jQuery's .text()?
  13. What is .toFixed()?
yqlim
  • 6,898
  • 3
  • 19
  • 43
  • I give up for this, however it won't work to my codes. there is no error found , I already change the class i will give update – DevGe Jan 11 '19 at 02:12
  • @DevGe saw your update, mate. You can't just copy paste it because it's only a **sample** code. You need to also make changes to your HTML to include the classes and change the codes to fit your HTML. I will update my code to be more descriptive. – yqlim Jan 11 '19 at 03:29
  • hi, thank you for the effort thank you I already understand .. thank you bro again. – DevGe Jan 11 '19 at 05:46
  • hi @Yong Quan, how to insert string currency like dollar? – DevGe Jan 11 '19 at 10:36
  • @DevGe lol keyboard key. Like how you inserted that symbol from your original code I guess? – yqlim Jan 11 '19 at 17:16
  • What i mean for this is if i tried to put $ or the string of currency the value turn to NAN – DevGe Jan 11 '19 at 17:48