I want to add rows and do math operation

Hello,

I’m trying to make a service form
I want to calculate the total cost by entering the materials and prices used during the repair

There is a default line as seen in the image below
I’m calculating in this default line
Ekran görüntüsü 2022-04-26 102346

How to calculate on new rows I add?
Ekran görüntüsü 2022-04-26 102712

Note: I will save the data on this page to the database.
To edit it again I will restore the page and remove or add lines

I tried to do something like below

Thank you from now

<script type="text/javascript">
number_format = function (number, decimals, dec_point, thousands_sep) {
      number = number.toFixed(decimals);

      var nstr = number.toString();
      nstr += '';
      x = nstr.split('.');
      x1 = x[0];
      x2 = x.length > 1 ? dec_point + x[1] : '';
      var rgx = /(\d+)(\d{3})/;

      while (rgx.test(x1))
          x1 = x1.replace(rgx, '$1' + thousands_sep + '$2');

      return x1 + x2;
  }

    $('.miktar,.birim_fiyati,.kdv_orani').on("keyup input", function(){
        var topla = 0;
        var kdv = 0;
        var kdv_dahil = 0;
        var kdv_orani = 0;
        var miktar = $('.miktar').val();
        var birim_fiyati = $('.birim_fiyati').val();
        var top = (miktar * birim_fiyati);
        var topla = number_format(top, 2, ',', '.');
        $('.tutar').val(topla);
        $('.toplam').val(topla);
        var kdorani = $('.kdv_orani').val();
        var kdvorani = kdorani.replaceAll('.', '');
        var kdv_orani = "1." + kdvorani;
        var sadece_kdv = "0." + kdvorani;
        var kdvdahil = (top * kdv_orani);
        var kdv_dahil = number_format(kdvdahil, 2, ',', '.');
        var kd = (top * sadece_kdv);
        var kdv = number_format(kd, 2, ',', '.');
        $('.kdv').val(kdv);
        $('.genel_toplam').val(kdv_dahil);
    });
</script>

<script type="text/javascript">
$(function(){
    $('#satirekle').on("click", ".addTaskRow", addTaskRow);
    $('#satirekle').on("click", ".removeTaskRow", removeTaskRow);
});

function addTaskRow() {
    addTableRow($('#satirekle #orta'));
}

function removeTaskRow() {
    var par = $(this).parent().parent();
    par.remove();
};

function addTableRow(table) {
    if($("[name='currency_unit']:checked").val()){
        var doviz = $("[name='currency_unit']:checked").val();
    }else{
        var doviz = '';
    }
    
    $(table).after(
        "<tr>" +
        "<td><input type='text' name='degisen[]' style='width:200px;'></td>" +
        "<td><input type='text' name='aciklama[]' style='width:300px;'></td>" +
        "<td><input type='text' name='miktar[]' value='0' class='miktar' style='width:75px;text-align:right;'></td>" +
        "<td><input type='text' name='birim[]' style='width:75px;'></td>" +
        "<td><input type='text' name='birim_fiyati[]' class='birim_fiyati' style='width:100px;text-align:right;'></td>" +
        "<td style='text-align:right;'><span class='tutar'></span><input type='hidden' name='tutar[]' class='tutar' style='width:150px;text-align:right;'> <span class='currency_unit'>" + doviz + "</span></td>" +
        "<td><a href='#s' style='color: #d9534f' class='removeTaskRow' title='Satırı Kaldır'><i class='fas fa-trash-alt'></i></a></td>" +
        "</tr>");
}
</script>

<script type="text/javascript">

  $(document).ready(function() {
    $('input[name="currency_unit"]').on('change',function(){
    if($(this).attr('value')){
        $('.currency_unit').text($(this).attr('value'));
    }
    });
  });

</script>

This is deprecated. You should be using .on instead.

The reason this doesn’t work for the dynamically added elements is because they don’t exist at the time the .bind/.on is executed. See the Delegated event handlers information at this link - .on() | jQuery API Documentation

You either need to attach the event handler to a container that the initial and dynamically added elements will be inside of or attach it to the document.

Thank you for the answer
I replaced .bind with .on
But I don’t know much about javascript, I need some more explanation

I have a question do you have that working? If that is the whole code then you are not loading the JQuery library as that isn’t Vanilla JavaScript.

That’s why I posted a link. You can also search on the web for - event handler doesn’t work for dynamically added elements.

Should work -

$(document).on('keyup input', '.miktar,.birim_fiyati,.kdv_oranir' , function() {

jquery library available
I’m doing this for myself, I’m not working

I looked at the link you gave, but it is not possible for me to understand that they will work for me because I have no knowledge of javascript / jquery

I don’t know how to do every line operation because the names of each line "name=“name[]” ", "class=“name” " will be the same

If you make substantial changes to your code, don’t edit the first post. The forum member(s) who saw the initial code don’t know that you even changed it. Post changed code as new replies in the thread.

You are going to need to post all the relevant code needed to produce the page in order for anyone to have a chance at helping, since any of the missing pieces that we might create won’t match what you have and won’t work when you try it.

Got it, didn’t know, thank you

Ok, I will prepare it to be published here

By the way, I was experimenting like below

$(document).on("keyup input", "#satirekle tr", function() {
    var tutar = 0.00;
    var miktar = $(this).find(".miktar").val();
    var birim_fiyati = $(this).find(".birim_fiyati").val();
    var tutar = (miktar * birim_fiyati);
    $(this).find(".tutar").val(tutar);
    $(this).find(".s_tutar").text(tutar);
 });

I don’t know how true this is
by trial and error
Ekran görüntüsü 2022-04-27 121338

All codes below
I will be glad if you help
I’m saving the data in this table as json to the sql database
I then put it in edit mode when needed
There will be add line or remove line features in edit mode

Thank you in advance

<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
 <!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js"></script>

<!-- Popper JS -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script> 

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

	<table class="table table" id="satirekle" width="100%">
		<tr class="bg-primary" style="color: white;text-align:center;">
			<th><b>DEĞİŞEN PARÇA</b></th>
			<th><b>AÇIKLAMA</b></th>
			<th><b>MİKTAR</b></th>
			<th><b>BİRİM</b></th>
			<th><b>BİRİM FİYATI</b></th>
			<th><b>TUTAR</b></th>
			<th>#</th>
		</tr>
		<tbody>

		<tr id="orta">
			<td><input type="text" name="degisen[]" style="width:200px;" required></td>
			<td><input type="text" name="aciklama[]" style="width:300px;" required></td>
			<td><input type="text" name="miktar[]" value="0" class="miktar" style="width:75px;text-align:right;" autocomplete="off" required></td>
			<td><input type="text" name="birim[]" style="width:75px;" required></td>
			<td><input type="text" name="birim_fiyati[]" value="0.00" class="birim_fiyati" style="width:100px;text-align:right;" autocomplete="off" required></td>
			<td style="text-align:right;"><span class="s_tutar">0.00</span><input type="hidden" name="tutar[]" class="tutar" style="width:150px;text-align:right;"> <span class="currency_unit"></span>
			</td>
			<td><a href="#s" style="color: #5cb85c;" class="addTaskRow" title="Yeni Satır Ekle"><i class="fa fa-plus"></i></a></td>
		</tr>

		<tr>
			<td colspan="5" style="text-align:right;">TOPLAM:</td>
			<td style="text-align:right;"><span class="toplam">0.00</span><input type="hidden" name="toplam" class="toplam" style="width:150px;text-align:right;"> <span class="currency_unit"></span></td>
			<td>&nbsp;</td>
		</tr>
		<tr>
			<td colspan="5" style="text-align:right;">KDV: % <input type="text" name="kdv_orani" class="kdv_orani" value="18.00" style="width:50px;text-align:right;" autocomplete="off" required></td>
			<td style="text-align:right;"><span class="kdv">0.00</span><input type="hidden" name="kdv" class="kdv" style="width:150px;text-align:right;"> <span class="currency_unit"></span></td>
			<td>&nbsp;</td>
		</tr>
		<tr>
			<td colspan="5" style="text-align:right;">GENEL TOPLAM:</td>
			<td style="text-align:right;"><span class="genel_toplam">0.00</span><input type="hidden" name="genel_toplam" class="genel_toplam" style="width:150px;text-align:right;"> <span class="currency_unit"></span></td>
			<td>&nbsp;</td>
		</tr>
		</tbody>
	</table>


	<script type="text/javascript">

	$(document).on("keyup input", "#satirekle tr", function() {
		var tutar = 0.00;
		var miktar = $(this).find(".miktar").val();
		var birim_fiyati = $(this).find(".birim_fiyati").val();
		var tut = (miktar * birim_fiyati);
		var tutar = number_format(tut, 2, ',', '.');
		$(this).find(".tutar").val(tutar);
		$(this).find(".s_tutar").text(tutar);
	 });
	 
	 
number_format = function (number, decimals, dec_point, thousands_sep) {
      number = number.toFixed(decimals);

      var nstr = number.toString();
      nstr += '';
      x = nstr.split('.');
      x1 = x[0];
      x2 = x.length > 1 ? dec_point + x[1] : '';
      var rgx = /(\d+)(\d{3})/;

      while (rgx.test(x1))
          x1 = x1.replace(rgx, '$1' + thousands_sep + '$2');

      return x1 + x2;
  }
  
	 
	$(function(){
		$('#satirekle').on("click", ".addTaskRow", addTaskRow);
		$('#satirekle').on("click", ".removeTaskRow", removeTaskRow);
	});

	function addTaskRow() {
		addTableRow($('#satirekle #orta'));
	}

	function removeTaskRow() {
		var par = $(this).parent().parent();
		par.remove();
	};

	function addTableRow(table) {
		if($("[name='currency_unit']:checked").val()){
			var doviz = $("[name='currency_unit']:checked").val();
		}else{
			var doviz = '';
		}
		
		$(table).after(
			"<tr>" +
			"<td><input type='text' name='degisen[]' style='width:200px;' required></td>" +
			"<td><input type='text' name='aciklama[]' style='width:300px;' required></td>" +
			"<td><input type='text' name='miktar[]' value='0' class='miktar' style='width:75px;text-align:right;' autocomplete='off' required></td>" +
			"<td><input type='text' name='birim[]' style='width:75px;' required></td>" +
			"<td><input type='text' name='birim_fiyati[]' value='0.00' class='birim_fiyati' style='width:100px;text-align:right;' autocomplete='off' required></td>" +
			"<td style='text-align:right;'><span class='s_tutar'>0.00</span><input type='hidden' name='tutar[]' class='tutar' style='width:150px;text-align:right;'> <span class='currency_unit'>" + doviz + "</span></td>" +
			"<td><a href='#s' style='color: #d9534f' class='removeTaskRow' title='Satırı Kaldır'><i class='fa fa-trash'></i></a></td>" +
			"</tr>");
	}
	
$(document).on('blur change keyup input', '.birim_fiyati,.kdv_orani,.s_tutar,.tutar' , function() {
        $(this).val(function (i, input) {
            input = input.replace(/\D/g, '');
            return (input / 100).toFixed(2);
        });
    }).trigger('blur');
	
	</script>

No sense re-inventing the wheel. What you are trying to do has been done a thousand times over. Here is an example of one…

https://codepen.io/tjoen/pen/wvgvLX

Here is an example of a complete database invoice system tutorial

2 Likes

Calculating and displaying the total, vat, and grand total, each time the row amount gets updated, is fairly straight forward. However, you should only apply number_format() to the displayed values, not the stored values (in the tutar fields.)

Add the following function -

// calculate and display the total, vat, and grand total
function calc_total(){
	var sum = 0;
	// loop over all the tutar fields
	$(".tutar").each(function(){
		var n = parseFloat($(this).val());
		sum += n;
	});
	// calculate vat and grand total
	var vat = $('.kdv_orani').val()/100 * sum;
	var gt = vat + sum;
	// format and display the values
	$('.toplam').text(number_format(sum, 2, ',', '.'));
	$('.kdv').text(number_format(vat, 2, ',', '.'));
	$('.genel_toplam').text(number_format(gt, 2, ',', '.'));
}

In the existing code, make the changes indicated by the comments -

$(document).on("keyup input", "#satirekle tr", function() {
	var tutar = 0.00;
	var miktar = $(this).find(".miktar").val();
	var birim_fiyati = $(this).find(".birim_fiyati").val();
	var tut = (miktar * birim_fiyati);
	var tutar = number_format(tut, 2, ',', '.');
	// change the following line to use tut instead of tutar
	$(this).find(".tutar").val(tut); // was tutar
	$(this).find(".s_tutar").text(tutar);
	// add the following line
	calc_total();
});

Also, in the removeTaskRow() function, call calc_total().

1 Like

Thank you for the answer
The billing system in the link you gave is very nice.
But not my bill. I am trying to add an option to add a service form, that is, a form describing the operations performed after the repair of the product, and if the material is used, under the form.

Thank you so much
worked perfectly
I fixed this error before I came to the forum, because number_format should not be used in the calculation field.

When I removed the line, its recalculation was perfect, thank you very much.

Sponsor our Newsletter | Privacy Policy | Terms of Service