0

我正在尝试将用户输入的值添加到每一行的 Slots 单元格中。我想获取总数并将其放在 SlotsTotals 字段中。但是,代码根本不起作用。

function checkRow(){
    var table = document.getElementById('tblSample');

    for (var i = 0, row; row = table.rows[i]; i++){
            document.getElementById('SlotsTotals').value += document.getElementById('txtSlots' + i).value;
    }
 }

我正在动态地将行添加到表中。用户将在槽字段中输入值。我想遍历表以获取所有值的总计,然后将总计添加到 SlotsTotal 字段。

这是我添加行的一些 html。

function addRow() {
    //function ValidateRow(){alert('error');}
    //function insertRow();

    var tbl = document.getElementById('tblSample');
    var lastRow = tbl.rows.length;  
    // if there's no header row in the table, then iteration = lastRow + 1
    //var iteration = lastRow;
    var iteration = lastRow;
    var row = tbl.insertRow(lastRow);

    var cell5 = row.insertCell(6);            
    var element5 = document.createElement('input');            
    element5.type = 'text';            
    element5.name = 'txtSlots' + iteration; 
    element5.id = 'txtSlots' + iteration;   
    element5.size = 10;
    cell5.appendChild(element5);
  }
4

1 回答 1

0

你能发布一些你的html代码吗

也许试试

document.getElementById('SlotsTotals').innerHTML

http://www.w3schools.com/jsref/met_doc_getelementbyid.asp

__

也许这可以帮助:)

<table id='tblSample' style='border: 1pt, solid, black;'>
  <tr>
    <td>
      ...A1
    </td>
    <td>
      ...A2
    </td>
    <td>
      ...A3
    </td>
    <td>
      ...A4
    </td>
    <td>
      ...A5
    </td>
    <td>
      <input type='text' id='txtSlots1'>
    </td>
  </tr>
  <tr>
    <td>
      ...B1
    </td>
    <td>
      ...B2
    </td>
    <td>
      ...B3
    </td>
    <td>
      ...B4
    </td>
    <td>
      ...B5
    </td>
    <td>
      <input type='text' id='txtSlots2'>
    </td>
  </tr>
  <tr>
    <td>
      ...C1
    </td>
    <td>
      ...C2
    </td>
    <td>
      ...C3
    </td>
    <td>
      ...C4
    </td>
    <td>
      ...C5
    </td>
    <td>
      <input type='text' id='txtSlots3'>
    </td>
  </tr>
  <tr>
    <td>
      ...D1
    </td>
    <td>
      ...D2
    </td>
    <td>
      ...D3
    </td>
    <td>
      ...D4
    </td>
    <td>
      ...D5
    </td>
    <td>
      <input type='text' id='txtSlots4'>
    </td>
  </tr>
 <tr>
    <td>
      ...E1
    </td>
    <td>
      ...E2
    </td>
    <td>
      ...E3
    </td>
    <td>
      ...E4
    </td>
    <td>
      ...E5
    </td>
    <td>
      <input type='text' id='txtSlots5'>
    </td>
  </tr>
</table>
<input type='button' onclick="test();" value="test">
<input type='text' id='SlotsTotals'>

<script>
  function test(){
    var table = document.getElementById('tblSample');
    res = document.getElementsByTagName('input');
    sum = 0
    for (var i = 0; i < res.length; i++){
      s = res[i].id
      if((String(s).indexOf("txtSlots") > -1)&&(res[i].type == 'text'))
      {
        sum += parseInt(res[i].value)
      }
    }
    document.getElementById('SlotsTotals').value = sum
  }
</script>
于 2013-03-06T18:03:39.967 回答