按钮单击后添加行后计算输入字段

时间:2016-12-01 22:03:58

标签: javascript jquery html

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

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

    我如何整合这些函数来计算在点击后显示的添加的新行中的天数和乘法?

1 个答案:

答案 0 :(得分:0)

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

您的主要问题(对添加的行进行计算)源于这样一个事实:您依靠类来唯一标识元素,但这不会削减它。每个新行和元素在行内需要有自己唯一的ID。

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

这个工作示例内联注释有助于了解正在发生的事情。

$(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>