如何从文本框数组中获取总值?

时间:2015-10-12 02:51:49

标签: javascript php jquery html

这是我的初始代码:我可以通过点击添加按钮添加文本框。

<script type="text/javascript">

function addRow(tableID) {

        var table = document.getElementById(tableID);

        var rowCount = table.rows.length;
        var row = table.insertRow(rowCount);

        var cell1 = row.insertCell(0);
        var element1 = document.createElement("input");
        element1.type = "text";
        element1.name = "txt1box[]";
        element1.id = "txt1Box[]";
        element1.size = "5";

        cell1.appendChild(element1);
        cell1.innerHTML = rowCount - 1 + 1;


        var cell2 = row.insertCell(1);
        var element2 = document.createElement("input");
        element2.type = "text";
        element2.name = "txt2box[]";
        element2.id = "txt2Box[]";
        element2.size = "68";
        cell2.appendChild(element2);

        //cell2.innerHTML = rowCount + 1;

        var cell3 = row.insertCell(2);
        var element3 = document.createElement("input");
        element3.type = "text";
        element3.name = "txt3box[]";
        element3.id = "txt3Box[]";
        cell3.appendChild(element3);

        var cell4 = row.insertCell(3);
        var element4 = document.createElement("input");
        element4.type = "text";
        element4.name = "txt4box[]";
        element4.id = "txt4Box[]";
        cell4.appendChild(element4);

        var cell5 = row.insertCell(4);
        var element5 = document.createElement("input");
        element5.type = "text";
        element5.name = "txt5box[]";
        element5.id = "txt5Box[]";
        element5.class = "txt5Box[]";
        cell5.appendChild(element5);


    }
        </script> 

问题是,它无法从添加的文本框中获取第一个可用文本框的值。如何从添加的文本框中获取值?

这是第一行已经可用。

<tr>
            <td width="10%">1</td>
            <td><input type="text" name="details[]" size="68"></td>
            <td><input type="text" name="qty[]"></td>
            <td><input type="text" name="unitprice[]"></td>
            <td><input class ="txt" type="text" name="totalamount[]"></td>
           </tr>

这是我的脚本,用于获取和总结文本框中的值。

<script>

      $(document).ready(function(){

          //iterate through each textboxes and add keyup
          //handler to trigger sum event
          $(".txt").each(function() {

              $(this).keyup(function(){
                  calculateSum();
              });
          });

      });

      function calculateSum() {

          var sum = 0;
          //iterate through each textboxes and add the values
          $(".txt").each(function() {

              //add only if the value is number
              if(!isNaN(this.value) && this.value.length!=0) {
                  sum += parseFloat(this.value);
              }

          });
          //.toFixed() method will roundoff the final sum to 2 decimal places
          $("#sum").html(sum.toFixed(2));
      }
  </script>

提前致谢!

0 个答案:

没有答案