【问题标题】:Calculate input field after row added when button click单击按钮时添加行后计算输入字段
【发布时间】:2016-12-01 22:03:58
【问题描述】:

我有一个自动进行 2 次计算的表格:

  1. 从带有日历的两个输入日期字段中选择到达和离开日期后的天数计算,结果存储在字段 (nbjours) 中
  2. 3 个字段的乘法(nbcheveaux * 天* 价格),结果存储在字段中(总计) 有一个按钮,当我们单击它时,会添加一个新行。如何在点击后添加的新闻行上重现相同的自动计算?

1- 我的添加行功能

window. addRow = function addRow(btn) {         
var parentRow = btn.parentNode.parentNode;
var table = parentRow.parentNode;
var tr = document.createElement("tr");
 var tdNbC = document.createElement("td");
var tdDateArrive = document.createElement("td");
var tdDateDepart = document.createElement("td");
var tdNbJour = document.createElement("td");
var tdPrix = document.createElement("td");
var tdTotal = document.createElement("td");
var td3 = document.createElement("td");
 var inputDateArrive = document.createElement("input");
 var inputDateDepart = document.createElement("input");
inputDateArrive.type = "text";
inputDateDepart.type = "text";
inputDateArrive.setAttribute("class", "date");
inputDateDepart.setAttribute("class", "date1");
var inputNbrC = document.createElement("input");
var inputNbrJour = document.createElement("input");
var inputPrix = document.createElement("input");
var inputTotal = document.createElement("input");
var inputButton = document.createElement("button");
inputButton.type = "button";
inputButton.innerHTML = "+";
inputButton.onclick = function(){
    addRow(this);  
};
tdNbC.appendChild(inputNbrC);
tdDateArrive.appendChild(inputDateArrive);
tdDateDepart.appendChild(inputDateDepart);
tdNbJour.appendChild(inputNbrJour);
tdPrix.appendChild(inputPrix);
tdTotal.appendChild(inputTotal);
td3.appendChild(inputButton);
 tr.appendChild(tdNbC);
 tr.appendChild(tdDateArrive);
tr.appendChild(tdDateDepart);
tr.appendChild(tdNbJour);
tr.appendChild(tdPrix);
tr.appendChild(tdTotal);
tr.appendChild(td3);
table.appendChild(tr);
$(inputDateDepart).mask("99/99/9999");
$(inputDateArrive).mask("99/99/9999");
}

2- 计算天数的函数

$(document).ready(function() {
 $('.date1').change(function() {
var start = $('.date').datepicker('getDate');
var end   = $('.date1').datepicker('getDate');
if (start<end) {
var days   = (end - start)/1000/60/60/24;
 $('.days').val(days);
 }
 else {
alert ("Depated date must be greater that arrived date!");
$('.date').val("");
$('.date1').val("");
$('.days').val("");
}
}); //end change function
}); //end ready

3- 操作乘法的函数

$('.nbrcevaux,.days,.price').keyup(function() {
var nbrcevaux = parseInt($('.nbrcevaux').val());
var days = parseInt($('.days').val());
var prix = parseInt($('.price').val());
$('.total').val(nbrcevaux * days * prix ); 
});

4- HTML 表格

       <table>
        <tr>
        <td class="centrer">Nbr de chevaux</td>
      <td class="centrer">Arrived Date</td>
       <td class="center">Departed Date</td>
       <td class="centrer">Nb/Days</td>
       <td class="centrer">Prix/jr/ cheval/boxe</td>
     <td class="centrer"> Total</td>

 </tr>
    <tr>
    <td><input type="text" name="nbrcevaux" class="nbrcevaux"  /></td>
        <td><input type="text" name="datearrive" class ="date"/> </td> 
        <td><input type="text" name="datedepart" class ="date1"  /></td>
        <td><input type="text" name="nbrjours" class ="days"  /></td>
        <td><input type="text" name="prix" class="price" /></td>
        <td><input type="text" name="total" class="total"  /></td>
          <td><button type="button" onClick ="addRow(this)">+</button>   </td>
     </tr>

如何在单击后显示的添加的新行中集成计算天数和乘法的函数?

【问题讨论】:

  • 首先,您的代码从一开始就是错误的,甚至无法运行。您从window. addRow 开始,而不是window.addRow,坦率地说,首先这是非常糟糕的做法(添加一个新的全局函数)。但是,您正在创建新的 td 元素并对其进行配置。你只是没有用任何数据填充它们。如果内容不是 HTML,则使用 element.textContent = newContent 执行此操作;如果内容是,请使用 element.innerHTML = newContent
  • 感谢您的评论,但我的代码工作正常..
  • 请不要担心在添加行功能中找到的代码数量。我想在添加行函数中集成计算函数,以便单击后添加的新行作为第一行...
  • window. addRow(您发布的第一行)会由于空格字符而导致语法错误。
  • 我安排好了..

标签: javascript jquery html


【解决方案1】:

所以,我很无聊并通过重写它来解决你的问题,因为你有很多多余的代码。

您的主要问题(关于添加的行的计算)源于您依赖类来唯一标识元素的事实,但这并不能解决问题。每个新行和元素行内需要有自己的唯一ID。

我还冒昧地确保只有一个“添加行”按钮,如您所见。

这个工作示例具有内联 cmets 以帮助跟踪正在发生的事情。

$(function() {

  // Declare & initialize module wide variables to store DOM elements:
  var $txtnbrcevaux = $("#nbrcevaux"), $txtDateArrive = $("#dateArrive"), 
      $txtDepart = $("#datedepart"), $txtnbrjours = $("#nbrjours"), $txtPrix = $("#prix"), 
      $txtTotal = $("#total"), $btnAdd = $("#btnAddRow"), $masterRow = $("#master1");
  
  // Unique value that will identify new elements
  var count = 1;
  
  // Establish the date picker fields
  $txtDateArrive.datepicker();
  $txtDepart.datepicker();
  
  // Wire up the button's click event:
  $btnAdd.on("click", function(){ 
      
    // Make a copy of the last row 
    var newTR =  $("tr[id=master" + count + "]").clone(true);
    
    // Update the new row's id to be unique
    newTR[0].id = "master" + (count + 1);
 
    // Loop through the child elements and modify their id's so that they are unique  
    newTR.children().each(function(index){
      if(this.children.length > 0){
        // Wipe out old (copied values)
        this.firstChild.value = "";
        var oldID = this.firstChild.id;
        this.firstChild.id = oldID.substring(0, oldID.length) + (count + 1);

        // Cloning datepickers creates problems because the clones remain bound to the
        // original input element. Here, we'll create a new input element and then 
        // insert it where the current one is, then we'll remove the current one:
        if($(this.firstChild).is(".date, .date1")){
          var newPicker = document.createElement("input");
          newPicker.id = this.firstChild.id;
          newPicker.name = this.firstChild.name;
          newPicker.setAttribute("class", this.firstChild.className.replace(" hasDatepicker", ""));
          newPicker.style.width = "80px";
          
          // Set up the new datepicker:
          $(newPicker).insertAfter(this.firstChild);
          $(this.firstChild).remove();
          $(newPicker).datepicker();
        }
      }
       

    });
  
    // Increment the count so the next row will use the next number for its id's  
    count++;
    
    // Hide the last row's button
    this.style.display = "none";    
  
    // Add the new row to the table
    $("table").append(newTR);  
 
    // Commented due to not having plugin available
    // $(inputDateDepart).mask("99/99/9999");
    // $(inputDateArrive).mask("99/99/9999");
  });

  $('.nbrcevaux, .days, .price').on("keyup", function() { 
    var nbrCevaux = this.parentElement.parentElement.querySelector(".nbrcevaux").value;
    var days = this.parentElement.parentElement.querySelector(".days").value;
    var prix = this.parentElement.parentElement.querySelector(".price").value; 
    
    // Your problem was that you were trying to work with values from
    // classes and not specific elements. Changing the function to expect
    // the data to be passed to it and having it return the answer allow
    // you to control what goes in and where to put what comes out
    this.parentElement.parentElement.querySelector(".total").value = nbrCevaux * days * prix;
  });
  
  $txtDepart.change(function() {
    var start = $txtDateArrive.datepicker('getDate');
    var end   = $txtDepart.datepicker('getDate');
    
    
    if (start < end) {
      var days   = (end - start)/1000/60/60/24;
      $txtnbrjours.val(days);
      
    } else {
      alert ("Depated date must be greater that arrived date!");
      $txtDateArrive.val("");
      $txtDepart.val("");
      $txtnbrjours.val("");
    }
  }); //end change function  
  
}); //end ready
/* This is only added to shrink things down so they appear within the space allotted */
input[type=text] {width:80px;}
body {font-size:.5em;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.3/jquery-ui.min.js"></script>
<table>       
  <tr>
    <td class="centrer">Nbr de chevaux</td>
    <td class="centrer">Arrived Date</td>
    <td class="center">Departed Date</td>
    <td class="centrer">Nb/Days</td>
    <td class="centrer">Prix/jr/ cheval/boxe</td>
    <td class="centrer"> Total</td>
  </tr>
  <tr id="master1">
    <td><input type="text" id="nbrcevaux" name="nbrcevaux" class="nbrcevaux"></td>
    <td><input type="text" id="dateArrive" name="dateArrive" class ="date"></td> 
    <td><input type="text" id="datedepart" name="dateDepart" class ="date1"></td>
    <td><input type="text" id="nbrjours" name="nbrjours" class ="days"></td>
    <td><input type="text" id="prix" name="prix" class="price"></td>
    <td><input type="text" id="total" name="total" class="total"></td>
    <td><button type="button" id="btnAddRow">+</button>   </td>
  </tr>
 </table>

【讨论】:

  • 您好,我已断开连接,非常感谢您抽出时间帮助我,我尝试阅读并理解您的代码。代码在 sn-p 上没有正确运行,只有第一行有效。当我把它们拿出来在浏览器中运行时,只有表格显示没有任何效果。
  • @BaptisteProphete 在上面的 sn-p 中,当我输入字段并选择日期时,会自动计算总数。这是在 keyup 事件上完成的,正如您所要求的。
  • 在 sn-p 中第一行和第二行正常工作,在其他行中日历不存储在输入日期字段中并且不计算天数..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-12
  • 2020-12-06
  • 1970-01-01
  • 2018-01-31
相关资源
最近更新 更多