使用javascript在表格中添加所有文本框值

时间:2014-10-18 07:09:35

标签: javascript jquery

我想使用jquery在表格中添加所有文本框值。

  <script>
    str =0;
   $(document).ready(function(){
       $('#btn_res').click(function(){
           $('#calculate').find("input[type=text]").each(function(){
               str+=$(this).text();
           })
           $('#result').text(str);
       });
   });
</script>

3 个答案:

答案 0 :(得分:1)

你需要

$(document).ready(function() {
  $('#btn_res').click(function() {
    var str = 0;
    $('#calculate').find("input[type=text]").each(function() {
      //need to use .val()
      //also need to convert it to a numerical value for addition else string concatenation will be done
      str += (+$(this).val() || 0);
    })
    $('#result').text(str);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="calculate">
  <tr>
    <td>
      <input type="text" />
    </td>
    <td>
      <input type="text" />
    </td>
  </tr>
  <tr>
    <td>
      <input type="text" />
    </td>
    <td>
      <input type="text" />
    </td>
  </tr>
  <tr>
    <td>
      <input type="text" />
    </td>
    <td>
      <input type="text" />
    </td>
  </tr>
</table>
<button id="btn_res">Sum</button>
<div id="result"></div>

答案 1 :(得分:0)

使用val()因为您正在获取表单输入字段值

$('#btn_res').click(function(){
           $('#calculate').find("input[type=text]").each(function(){
               str+=$(this).val();
           })
           $('#result').text(str);
       });

答案 2 :(得分:0)

我自己的建议如下:

$(document).ready(function() {
  $('#btn_res').click(function() {
    // find all the relevant input elements directly (no need
    // to use 'find()'; then iterate over those elements with 'map()':
    var str = $('#calculate input[type="text"]').map(function() {
      // this returns the value of the input (as a number) or a 0 (if
      // the input is not a valid number):
      return parseFloat((this.value || 0));
    // 'get()' converts the object to an array,
    // 'reduce' reduces the array to a single result:
    }).get().reduce(function(a, b) {
      // returns the sum of the array's elements:
      return a + b;
    });
    $('#result').text(str);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="calculate">
  <tr>
    <td>
      <input type="text" />
    </td>
    <td>
      <input type="text" />
    </td>
  </tr>
  <tr>
    <td>
      <input type="text" />
    </td>
    <td>
      <input type="text" />
    </td>
  </tr>
  <tr>
    <td>
      <input type="text" />
    </td>
    <td>
      <input type="text" />
    </td>
  </tr>
</table>
<button id="btn_res">Sum</button>
<div id="result"></div>

参考文献: