Javascript添加行并从html计算多行

时间:2019-05-10 09:43:46

标签: javascript html

我找到了帖子Add new row and calculate seperate value from html table。这类似于我要寻找的内容,但是我想将其总和保存为变量以在另一个公式中使用总和。我该如何实现?我已经做了很多尝试,但是还没有找到真正的解决方案。位置1的结果是正确的,但其他所有结果均被忽略 本来它应该看起来像这样。 Form

//Calculate Tip
function calculateTip() {
  var montcost = 500;
  var kamera = document.getElementById("kamera1").value;
  var anzahl = document.getElementById("anzahl1").value;
  var laufzeit = document.getElementById("laufzeit").value;
  var datccost = 30;



  //Calculate tip
  var total = ((montcost + (kamera * anzahl)) / laufzeit) + (datccost);
  //round to two decimal places
  total = Math.round(total * 100) / 100;
  //next line allows us to always have two digits after decimal point
  total = total.toFixed(0);
  //Display the tip
  document.getElementById("totalTip").style.display = "block";
  document.getElementById("tip").innerHTML = total;

}

//Hide the tip amount on load
//document.getElementById("totalTip").style.display = "none";
//document.getElementById("each").style.display = "none";

//click to call function
document.getElementById("calculate").onclick = function() {
  calculateTip();

};

function numberingTableRow(){
  $.each($('#numberingTable tbody tr'), function (i, v) {
            $(this).find('td:eq(0)').html(i+1);
        });
}

  


var counter = 2;

// Function to increment counter
function addRow() {
  counter += 1;
}
//' + counter +'
$(document).on('click','.btnAddRowTable',function(e){
  e.stopPropagation();
  $('#numberingTable tbody').append('<tr><td></td><td><select id="kamera"><option selected value="0">Kamera auswählen</option><option value="500">Kamera 1</option><option value="600">Kamera 2</option><option value="700">Kamera 3</option><option value="800">Kamera 4</option><option value="900">Kamera 5</option></select></td><td><select id="anzahl"><option selected value="0">Anzahl</option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option><option value="10">10</option><option value="11">11</option><option value="12">12</option></select></td><td><button type="button" class="btn btn-xs btn-danger btnDeleteRowTable">Delete</button></td></tr>');
  numberingTableRow();
  addRow();

});

$(document).on('click','.btnDeleteRowTable',function(e){
  e.stopPropagation();
  $(this).parent().parent().remove();
  numberingTableRow();
});
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>Javascript Tip Calculator</title>




</head>

<body>

  <div id="calculator">


    <form>

      <table id="numberingTable" class="table table-hover table-sm">
        <thead>
          <tr>
            <th>No</th>
            <th>Kamera</th>
            <th></th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>1</td>
            <td> <select id="kamera1">
            <option selected value="0">Choose Model</option>
            <option value="500">Model 1</option>
            <option value="600">Model 2</option>
            <option value="700">Model 3</option>
            <option value="800">Model 4</option>
            <option value="900">Model 5</option>
            </select> </td><td>
              <select id="anzahl1">
              <option selected value="0">Qty</option>
              <option value="1">1</option>
              <option value="2">2</option>
              <option value="3">3</option>
              <option value="4">4</option>
              <option value="5">5</option>
              <option value="6">6</option>
              <option value="7">7</option>
              <option value="8">8</option>
              <option value="9">9</option>
              <option value="10">10</option>
              <option value="11">11</option>
              <option value="12">12</option>
              </select>
              </td>
            <td><button type="button" class="btn btn-xs btn-danger btnDeleteRowTable">Delete</button></td>
          </tr>

        </tbody>

      </table>

      <br/>
      <br/>
      <button type="button" class="btn btn-xs btn-primary btnAddRowTable">Add article</button>


                <p>Whitch duration?</p>
                <select id="laufzeit">
                <option value="12">12 Monate</option>
                <option value="18">18 Monate</option>
                <option value="24">24 Monate</option>
                </select>


      </form>



      <button type="button" id="calculate">Calculate!</button>


  <!--calculator end-->
  <div id="totalTip">
    <sup>€</sup><span id="tip">0.00</span>
    <small id="each">Monatlich</small>
  </div></div>
<!--container end-->

<script type="text/javascript" src="tipcalculator.js"></script>


<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>





</body>

</html>

1 个答案:

答案 0 :(得分:0)

也许您需要修改函数calculateTip,以便为它提供执行计算所需的行号作为参数,并针对每一行运行此函数。

请注意,您不应有多个共享相同ID的元素。 您还需要重构HTML,以便可以通过不同的ID查找每个元素,例如:

  var kamera = document.getElementById("kamera[0]").value;
  var anzahl = document.getElementById("anzahl[0]").value;

最后,您只需要使用跟踪行数的变量,并要求更新的calculateTip计算每一行的总和,并在getTotalSum中收集最终的总和即可。

更新: 完整的解决方案,如所承诺的那样:)

对于没有选定质量或模型的情况,您还应该添加一些额外的逻辑来计算价格,您应该能够完成这些额外的检查,作为作业...

干杯!

$( document ).ready(function() {

  //Calculate Tip
function calculateTip(id = 0) {
  var montcost = 500;
  var kamera = document.getElementById('kamera['+id+']').value;
  var anzahl = document.getElementById('anzahl['+id+']').value;
  var laufzeit = document.getElementById('laufzeit').value;
  var datccost = 30;

  //Calculate tip
  var total = ((montcost + (kamera * anzahl)) / laufzeit) + (datccost);
  return Math.round(total * 100);
}
function getTotalSum() {
  var totalSum = 0;
  var nbr = getCounter();
  for (var cid = 0; cid <= nbr; cid++) {
   //we add sums as integers to avoid floating point errors
   totalSum += calculateTip(cid);
  }
  //Display the tip
  document.getElementById('totalTip').style.display = 'block';
  document.getElementById('tip').innerHTML = (totalSum / 100).toFixed(2); //the final number is presented as it should be rounded to 2 digits after zero!
}

//Hide the tip amount on load
//document.getElementById("totalTip").style.display = "none";
//document.getElementById("each").style.display = "none";

//click to call function
document.getElementById("calculate").onclick = function() {
  getTotalSum();
};

function numberingTableRow(){
  $.each($('#numberingTable tbody tr'), function (i, v) {
       $(this).find('td:eq(0)').html(i+1);
  });
}

var counter = 0; //we can start counting rows from zero, as we like having fun ;)
// Function to increment counter
function addRow() {
  counter += 1;
}
function removeRow() {
  counter -= 1;
}
function getCounter() {
  return counter;
}
//' + counter +'
$(document).on('click','.btnAddRowTable',function(e){
  e.stopPropagation();
  addRow(); //we increase the counter as we are about to add a new row
  counter = getCounter();
  $('#numberingTable tbody').append('<tr><td></td><td><select id="kamera['+counter+']"><option selected value="0">Kamera auswählen</option><option value="500">Kamera 1</option><option value="600">Kamera 2</option><option value="700">Kamera 3</option><option value="800">Kamera 4</option><option value="900">Kamera 5</option></select></td><td><select id="anzahl['+counter+']"><option selected value="0">Anzahl</option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option><option value="10">10</option><option value="11">11</option><option value="12">12</option></select></td><td><button type="button" class="btn btn-xs btn-danger btnDeleteRowTable">Delete</button></td></tr>');
  numberingTableRow();
});

$(document).on('click','.btnDeleteRowTable',function(e){
  e.stopPropagation();
  $(this).parent().parent().remove();
  removeRow();
  numberingTableRow();
});
});
<!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8">
  <title>Javascript Tip Calculator</title>
</head>

<body>
<!--container start-->
  <div id="calculator">
	<form>
		<table id="numberingTable" class="table table-hover table-sm">
			<thead>
				<tr>
					<th>No</th>
					<th>Kamera</th>
					<th></th>
				</tr>
			</thead>
			<tbody>
				<tr>
					<td>1</td>
					<td>
						<select id="kamera[0]">
							<option selected value="0">Choose Model</option>
							<option value="500">Model 1</option>
							<option value="600">Model 2</option>
							<option value="700">Model 3</option>
							<option value="800">Model 4</option>
							<option value="900">Model 5</option>
						</select>
					</td>
					<td>
						<select id="anzahl[0]">
							<option selected value="0">Qty</option>
							<option value="1">1</option>
							<option value="2">2</option>
							<option value="3">3</option>
							<option value="4">4</option>
							<option value="5">5</option>
							<option value="6">6</option>
							<option value="7">7</option>
							<option value="8">8</option>
							<option value="9">9</option>
							<option value="10">10</option>
							<option value="11">11</option>
							<option value="12">12</option>
						</select>
					</td>
					<td><button type="button" class="btn btn-xs btn-danger btnDeleteRowTable">Delete</button></td>
				</tr>
			</tbody>
		</table>
		<br/>
		<br/>
		<button type="button" class="btn btn-xs btn-primary btnAddRowTable">Add article</button>
		<p>Whitch duration?</p>
		<select id="laufzeit">
			<option value="12">12 Months</option>
			<option value="18">18 Months</option>
			<option value="24">24 Months</option>
		</select>
	</form>
	<button type="button" id="calculate">Calculate!</button>
	<div id="totalTip">
		<sup>€</sup><span id="tip">0.00</span>
		<small id="each">Monatlich</small>
	</div>
</div>
<!--container end-->

<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<script type="text/javascript" src="tipcalculator.js"></script>

</body>
</html>