javascript - 动态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”。
解决方案
获取表中的行数。添加 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。
推荐阅读
- css - -webkit-transform:rotateY 在 Mac OS 上失败
- reactjs - 由于数组反应原生而无法获取 api
- python - 使用 scikit-learn 管道与手动操作时的不同分数
- python - 为 Keras 重塑一维 Numpy 数组
- python-3.x - 如何使用 BeautifulSoup 访问元素属性?
- javascript - Javascript通过布尔属性从Neo4j过滤器中获取数据
- python - python3.7版本的aws-sam-cli包的pip安装
- c# - 如何在外部应用程序上呈现内部 PowerBI 报表服务器报表?
- access-control - 如何找到 ARA-M 示例 APDU?
- mongodb - 使用 $in 查找文档,使用另一个文档的数组