首页 > 解决方案 > 动态Javascript增加复选框的值

问题描述

我无法自动增加位于表格内的复选框的值。因此,简而言之,在我的 HTML 表格中,我有文本框和一个复选框作为一行显示(加载网页时默认显示 5 行)。我有一个按钮,可以调用下面的 javascript 来自动克隆一行,如果最终用户想要在这个现有的默认 5 行 HTML 表中添加更多行。

<script type="text/javascript">
function cloneRow() {
      var table = document.getElementById("tableToModify"); // find table to append to
      var row = document.getElementById("rowToClone");
      var clone = row.cloneNode(true); // copy children too
      clone.id = "newID"; // change id or other attributes/contents
      table.appendChild(clone); // add new row to end of table
    }

// This function deletes a row when clicked on the button
function deleteRow(r) {
  var i = r.parentNode.parentNode.rowIndex;
  document.getElementById("myTable").deleteRow(i);
}

现在在我的 HTML 中,复选框如下所示: PS:值“3”表示行数,因此在此示例中,此复选框位于第 3 行。

<tr id="rowToClone">
        <td id="Transportation_Type">
            <select id="Transportation_Type" onChange="checkOption(this)" name="transportation_type">
                {% for type in transportation_type %}
                <option value="{{ type.type }}">{{ type.type }}</option>
                {% endfor %}
            </select>
        </td>
        <td><input type="text" id="License_Plate" name="License_Plate" placeholder="Optional" style="text-align:center;" disabled></td>
        <td><input id="checkbox" type="checkbox" name="Electric" value="3"/></td>
        <td id="Number of days per week" >
            <select name="DaysPerWeek">
                <option selected>1</option>
                <option>2</option>
                <option>3</option>
                <option>4</option>
                <option>5</option>
            </select>
        </td>
        <td><input type="number" name="DistanceInKm" style="text-align:center;" ></td>
        <td><button class="button is-danger "  onclick="deleteRow(this)">Delete Row</button></td>
    </tr>

所以现在我的问题是当单击克隆按钮时,新行将如何获得复选框中的下一个值?

假设最终用户单击一次clone button,则复选框和其他复选框将被克隆,但只有复选框的值应自动为“6”。

标签: javascript

解决方案


获取表中的行数。添加 1 以获得复选框的适当值。

function cloneRow() {
  var table = document.getElementById("tableToModify"); // find table to append to
  var row = document.getElementById("rowToClone");
  var clone = row.cloneNode(true); // copy children too
  clone.id = "newID"; // change id or other attributes/contents
  var rows = table.querySelectorAll("tr").length;
  clone.querySelector("input[type=checkbox]").value = rows+1;
  table.appendChild(clone); // add new row to end of table
}

如果表格中有不应计算的标题行,则不要加 1。


推荐阅读