更改innerhtml输入框值

时间:2017-09-01 11:47:03

标签: javascript jquery html

我必须在html表中添加新行,它从第一行生成文本框作为内部html,并显示第一行的文本。

在图片中,当我按“添加语言”按钮时,您会看到最后一行与第一行相同。但是我希望新行应该是空白的。 enter image description here

function addRow(tableID) {
    var table = document.getElementById(tableID);
    var rowCount = table.rows.length;

                            // limit the user from creating fields more than your limits
        var row = table.insertRow(rowCount);
        var colCount = table.rows[0].cells.length;
        for(var i=0; i<colCount; i++) {
            var newcell = row.insertCell(i);
            newcell.innerHTML = table.rows[1].cells[i].innerHTML;


        }

我放了$('.small').val('Some text');,但文本框就消失了。

请注意页面上有多个表格,我们使用相同的功能来生成行。

2 个答案:

答案 0 :(得分:1)

您需要清理文本框才能将其清空。你已经用jQuery的标记标记了这个,所以这是我的解决方案。

&#13;
&#13;
function addNewRow(ID) {
  var table = $("#" + ID);
  var cloneRow = $("tr:eq(1)", table).clone();

  //Clean out all textboxes
  $("td input:text", cloneRow).removeAttr('value')

  $("tbody", table).prepend(cloneRow)
}

$('button').click(function() {
  addNewRow("test")
})
&#13;
table {
  width: 100%;
  margin-bottom: 20px;
  border-collapse: collapse;
}

table,
th,
td {
  border: 1px solid #cdcdcd;
}

table th,
table td {
  padding: 10px;
  text-align: left;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table id="test">
  <thead>
    <tr>
      <th>Select</th>
      <th>Value 1</th>
      <th>Value 2</th>
      <th>Value 3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>
        <input type="checkbox" name="record">
      </td>
      <td>
        <input type="text" name="record" value="Value 1">
      </td>
      <td>
        <input type="text" name="record" value="Value 2">
      </td>
      <td>
        <input type="text" name="record" value="Value 3">
      </td>
    </tr>
    <tr>
      <td>
        <input type="checkbox" name="record">
      </td>
      <td>
        <input type="text" name="record" value="Value 1">
      </td>
      <td>
        <input type="text" name="record" value="Value 2">
      </td>
      <td>
        <input type="text" name="record" value="Value 3">
      </td>
    </tr>
  </tbody>
</table>

<button type="button">Add row!</button>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以使用以下方法清空第一行的输入字段:

$("table tr:first input").val("");

这将:

$("table                     //Select the table
         tr:first            //Pick the first row in that table
                  input      //Take the input fields from that first row
                       ").val("");
相关问题