向HTML表添加行的按钮破坏了我的自动计算功能

时间:2019-02-08 15:07:09

标签: javascript jquery html

我必须创建一个具有多个自动添加值行的表,其中值会自动计数。并显示值的小计。我尝试一下,它在第一行中有效,但在第二行中则无效。我提供了屏幕截图和我的cdes。有没有人解决这个问题?

enter image description here

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
		<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
	var i=1;
	$('#add').click(function(){
		i++;
		$('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" name="qty[]" id="qty1" placeholder="Enter your Qty" class="form-control name_list" /></td><td><input type="text" name="rate[]" id="rate1" placeholder="Enter your Rate" class="form-control name_list" /></td><td><input type="text" name="total[]" id="sum" class="form-control name_list" disabled /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
	});
	
	$(document).on('click', '.btn_remove', function(){
		var button_id = $(this).attr("id"); 
		$('#row'+button_id+'').remove();
	});
	
	$('#submit').click(function(){		
		$.ajax({
			url:"name.php",
			method:"POST",
			data:$('#add_name').serialize(),
			success:function(data)
			{
				alert(data);
				$('#add_name')[0].reset();
			}
		});
	});
	
});
</script>
 <script>
$(document).ready(function() {
	//this calculates values automatically 
	sum();
	$("#qty1, #rate1").on("keydown keyup", function() {
		sum();
	});
});

function sum() {
			var qty1 = document.getElementById('qty1').value;
			var rate1 = document.getElementById('rate1').value;
			var result = parseInt(qty1) * parseInt(rate1);
			if (!isNaN(result)) {
				document.getElementById('sum').value = result;
			}
		}
</script>
<html>
	<head>
		<title></title>
		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
		
	</head>
	<body>
		<div class="container">
			<div class="form-group">
				<form name="add_name" id="add_name">
					<div class="table-responsive">
						<table class="table table-bordered" id="dynamic_field">
							<tr>
								<td><input type="text" name="qty[]" id="qty1" placeholder="Enter your Qty" class="form-control name_list" /></td>
								<td><input type="text" name="rate[]" id="rate1" placeholder="Enter your Rate" class="form-control name_list" /></td>
								<td><input type="text" name="total[]" id="sum" class="form-control name_list" disabled /></td>
								<td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
							</tr>
						</table>
						<table class="table table-bordered" id="dynamic_field">
							<tr>
								<td></td>
								<td>Total</td>
								<td><input type="text" name="subtotal" id="allsum" class="form-control name_list" disabled /></td>
								<td></td>
							</tr>
						</table>
						<input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />
					</div>
				</form>
			</div>
		</div>
	</body>
</html>

3 个答案:

答案 0 :(得分:2)

您有为<tr>创建唯一ID的正确想法,只需为其他ID使用相同的技术即可。

请注意,您可以告诉jQuery选择所有以 某些字符开头的ID :{{1 }}

但是使用$('[id^=qty], [id^=rate]')时,必须将.on()附加到上面要添加新行的位置。就是说,如果您告诉它观看.on(),那么它将是观看的内容-已经存在的一行。由于在 中未添加任何内容,因此$('[id^=qty], [id^=rate]')将不会触发。您需要观看一个已经存在的元素,并在其中添加内容。由于新内容已添加到.on(),因此我们可以使用它来触发document.on()也可以使用...就像在DOM上到添加新内容的父级上一样。

这叫做event delegation,非常值得花两分钟阅读。您可能还需要花两分钟时间仔细检查event propagation,并快速查看javascript events.。阅读这三篇文章所需的总时间-大约十分钟。他们将为您节省此项目的总时间:可能几个小时。

作为练习,请查看您距离要添加的行有多近(即,将$('body').on()替换为$(document),并查看$('#dynamic_field')是否仍被触发。

.on()
$(document).ready(function(){
	var i=1;
  
	$('#add').click(function(){
		i++;
		$('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" name="qty[]" id="qty'+i+'" placeholder="Enter your Qty" class="form-control name_list" /></td><td><input type="text" name="rate[]" id="rate'+i+'" placeholder="Enter your Rate" class="form-control name_list" /></td><td><input type="text" name="total[]" id="sum'+i+'" class="form-control name_list" disabled /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
	});
	
	$(document).on('click', '.btn_remove', function(){
		var button_id = $(this).attr("id"); 
		$('#row'+button_id+'').remove();
	});
	
	$('#submit').click(function(){		
		$.ajax({
			url:"name.php",
			method:"POST",
			data:$('#add_name').serialize(),
			success:function(data)
			{
				alert(data);
				$('#add_name')[0].reset();
			}
		});
	});
	

	//this calculates values automatically 
	$(document).on("keyup", "[id^=qty], [id^=rate]", function() {
    var numm = this.id.match(/\d+/g);
    //var letr = this.id.match(/[a-zA-Z]+/g);
    sum(numm);
	});

function sum(i) {
			var qty1 = $('#qty'+i).val();
			var rate1 = $('#rate'+i).val();
			var result = parseInt(qty1) * parseInt(rate1);
			if (!isNaN(result)) {
				$('#sum'+i).val(result);
        sum_total();
			}
}
function sum_total(){
   $('#allsum').val('Ready for you to write this fn');
   //you do this one - hint: use jQuery $.each() to loop through all the SUM ids, and then update the #allsum input in the #submit_field table.
}

}); //end document.ready


根据Cale B的明智建议,此处是使用类代替ID的相同示例(在方便之处)。请注意,您可以使用简单的类名,而不是更复杂的 开头的 选择器语法-,但是知道选择器语法的开始非常酷

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
		<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div class="container">
			<div class="form-group">
				<form name="add_name" id="add_name">
					<div class="table-responsive">
						<table class="table table-bordered" id="dynamic_field">
							<tr id="row1">
								<td><input type="text" name="qty[]" id="qty1" placeholder="Enter your Qty" class="form-control name_list" /></td>
								<td><input type="text" name="rate[]" id="rate1" placeholder="Enter your Rate" class="form-control name_list" /></td>
								<td><input type="text" name="total[]" id="sum1" class="form-control name_list" disabled /></td>
								<td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
							</tr>
						</table>
						<table class="table table-bordered" id="submit_field">
							<tr>
								<td></td>
								<td>Total</td>
								<td><input type="text" name="subtotal" id="allsum" class="form-control name_list" disabled /></td>
								<td></td>
							</tr>
						</table>
						<input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />
					</div>
				</form>
			</div>
		</div>
$(document).ready(function(){
	var i=1;
  
	$('#add').click(function(){
		i++;
		$('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" name="qty[]" id="qty'+i+'" placeholder="Enter your Qty" class="form-control name_list qty_cls" /></td><td><input type="text" name="rate[]" id="rate'+i+'" placeholder="Enter your Rate" class="form-control name_list rate_cls" /></td><td><input type="text" name="total[]" id="sum'+i+'" class="form-control name_list sum_cls" disabled /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
	});
	
	$(document).on('click', '.btn_remove', function(){
		var button_id = $(this).attr("id"); 
		$('#row'+button_id+'').remove();
	});
	
	$('#submit').click(function(){		
		$.ajax({
			url:"name.php",
			method:"POST",
			data:$('#add_name').serialize(),
			success:function(data)
			{
				alert(data);
				$('#add_name')[0].reset();
			}
		});
	});
	

	//this calculates values automatically 
	$(document).on("keyup", ".qty_cls, .rate_cls", function() {
    var numm = this.id.match(/\d+/g);
    //var letr = this.id.match(/[a-zA-Z]+/g);
    sum(numm);
	});

function sum(i) {
			var qty1 = $('#qty'+i).val();
			var rate1 = $('#rate'+i).val();
			var result = parseInt(qty1) * parseInt(rate1);
			if (!isNaN(result)) {
				$('#sum'+i).val(result);
        sum_total();
			}
}
function sum_total(){
   $('#allsum').val('Ready for you to write this fn');
   //you do this one - hint: use jQuery $.each() to loop through all the SUM ids, and then update the #allsum input in the #submit_field table.
}

}); //end document.ready

答案 1 :(得分:0)

经过一些更改后,我得到了几乎解决方案,但是仅在单击“添加按钮”时刷新每一行的总计。也许您可以从这里找到最终的解决方案:

<script>
$(document).ready(function(){
  var i=1;
  $('#add').click(function(){
    i++;
    $('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" name="qty[]" id="qty'+i+'" placeholder="Enter your Qty" class="form-control name_list" /></td><td><input type="text" name="rate[]" id="rate'+i+'" placeholder="Enter your Rate" class="form-control name_list" /></td><td><input type="text" name="total[]" id="sum'+i+'" class="form-control name_list" disabled /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
    sum();
  });

  $(document).on('click', '.btn_remove', function(){
    var button_id = $(this).attr("id"); 
    $('#row'+button_id+'').remove();
  });

  $('#submit').click(function(){    
    $.ajax({
      url:"name.php",
      method:"POST",
      data:$('#add_name').serialize(),
      success:function(data)
      {
        alert(data);
        $('#add_name')[0].reset();
      }
    });
  });

});
</script>
 <script>
$(document).ready(function() {
  //this calculates values automatically 
  sum();
  $.each($("input[name='qty[]'], input[name='rate[]'"), function() {
    $(this).on("blur", function(e) {
      sum();
    });
  });
});

function sum() {
  $.each($("input[name='qty[]']"), function() {
    var id = $(this).attr("id");

    /*console.log(document.getElementById('qty'+id[id.length - 1]).value);
    console.log(document.getElementById('rate'+id[id.length - 1]).value);*/

    var qty1 = document.getElementById('qty'+id[id.length - 1]).value;
    var rate1 = document.getElementById('rate'+id[id.length - 1]).value;
    var result = parseInt(qty1) * parseInt(rate1);
    if (!isNaN(result)) {
      document.getElementById('sum'+id[id.length - 1]).value = result;
    }
  });

    }
</script>

<html>
  <head>
    <title></title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />

  </head>
  <body>
    <div class="container">
      <div class="form-group">
        <form name="add_name" id="add_name">
          <div class="table-responsive">
            <table class="table table-bordered" id="dynamic_field">
              <tr>
                <td><input type="text" name="qty[]" id="qty1" placeholder="Enter your Qty" class="form-control name_list" /></td>
                <td><input type="text" name="rate[]" id="rate1" placeholder="Enter your Rate" class="form-control name_list" /></td>
                <td><input type="text" name="total[]" id="sum1" class="form-control name_list" disabled /></td>
                <td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
              </tr>
            </table>
            <table class="table table-bordered" id="dynamic_field">
              <tr>
                <td></td>
                <td>Total</td>
                <td><input type="text" name="subtotal" id="allsum" class="form-control name_list" disabled /></td>
                <td></td>
              </tr>
            </table>
            <input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />
          </div>
        </form>
      </div>
    </div>
  </body>
</html>

答案 2 :(得分:0)

这应该是一项功能全面的测试,包括您的总计。请注意,我确保每个相关元素都有一个唯一的ID,并且在使用这些唯一ID创建元素时,事件处理程序已添加到每个元素中。

<script
  src="https://code.jquery.com/jquery-2.2.4.js"
  integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI="
  crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>


<script>
var i=0;
$(document).ready(function(){
    $('#add').click(function(){
        i++;
        $('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" name="qty['+i+']" id="qty'+i+'"  placeholder="Enter your Qty" class="form-control name_list qty" /></td><td><input type="text" name="rate['+i+']" id="rate'+i+'"  placeholder="Enter your Rate" class="form-control name_list rate" /></td><td><input type="text" name="total[]" id="sum'+i+'" class="form-control name_list" disabled /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
        $('#qty'+i+', #rate'+i).change(function() {
            sum(i)
        });
    });

    $(document).on('click', '.btn_remove', function(){
        var button_id = $(this).attr("id"); 
        $('#row'+button_id+'').remove();
        sum_total();
    });

    $('#submit').click(function(){      
        $.ajax({
            url:"name.php",
            method:"POST",
            data:$('#add_name').serialize(),
            success:function(data)
            {
                alert(data);
                $('#add_name')[0].reset();
            }
        });
    });

});

$(document).ready(function() {
    //this calculates values automatically 
    sum(0);
});

function sum(i) {
    var qty1 = document.getElementById('qty'+i).value;
    var rate1 = document.getElementById('rate'+i).value;
    var result = parseInt(qty1) * parseInt(rate1);
    if (!isNaN(result)) {
        document.getElementById('sum'+i).value = result;
    }
    sum_total();
}
function sum_total() {
    var newTot = 0;
    for (var a=0; a<=i ; a++) {
        aVal = $('#sum'+a);
        if (aVal && aVal.length) { newTot += aVal[0].value ? parseInt(aVal[0].value) : 0; }
    }
    document.getElementById('allsum').value = newTot;
}
</script>

<html>
    <head>
        <title></title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />

    </head>
    <body>
        <div class="container">
            <div class="form-group">
                <form name="add_name" id="add_name">
                    <div class="table-responsive">
                        <table class="table table-bordered" id="dynamic_field">
                            <tr>
                                <td><input type="text" name="qty[0]" id="qty0" onchange="sum(0)" placeholder="Enter your Qty" class="form-control name_list" /></td>
                                <td><input type="text" name="rate[0]" id="rate0" onchange="sum(0)" placeholder="Enter your Rate" class="form-control name_list" /></td>
                                <td><input type="text" name="total[0]" id="sum0" class="form-control name_list" disabled /></td>
                                <td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
                            </tr>
                        </table>
                        <table class="table table-bordered" id="dynamic_field">
                            <tr>
                                <td></td>
                                <td>Total</td>
                                <td><input type="text" name="subtotal" id="allsum" class="form-control name_list" disabled /></td>
                                <td></td>
                            </tr>
                        </table>
                        <input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />
                    </div>
                </form>
            </div>
        </div>
    </body>
</html>