[英]Javascript change value of attribute of firstChild
The problem: I'm duplicating div's using a button. 问题:我正在使用按钮复制div。 Within the div's are parts of a form:
div内是表单的一部分:
<form method="post" action="order-opstellen.php">
<div id="duplicate">
<input type="hidden" id="counter" value="0">
</div>
<input type="button" onclick="duplicate()" value="Add">
<button type="submit">Send</button>
</form>
I'm using this script: 我正在使用此脚本:
<script type="text/javascript">
var i = 0;
var original = document.getElementById('duplicate');
function duplicate() {
var clone = original.cloneNode(true);
clone.id = "duplicate" + ++i;
clone.style.clear = "both";
original.parentNode.appendChild(clone);
var tempId = document.getElementById("duplicate" + i);
tempId.childNodes[0].value=i;
}
</script>
As you can see, I'm trying to change the value of each input. 如您所见,我正在尝试更改每个输入的值。 Adding it with 1 every time I duplicate the div.
每次复制div时,将其加1。 Obviously it is not working.
显然它不起作用。 How do I do this?
我该怎么做呢?
Update: 更新:
So I've got this first part working. 所以我已经开始工作了。 Now I need to go deeper.
现在我需要更深入。
<form method="post" action="order-opstellen.php">
<div id="duplicate">
<input type="hidden" id="counter" value="0">
<div class="form-group dispWidth fl">
<label>Productnaam</label>
<select class="form-control dispWidth" name="productnaam"> <?php
$sql_products = "SELECT * FROM product ORDER BY naam";
$results = $conn->query($sql_products)->fetchAll(PDO::FETCH_OBJ);
foreach ($results as $row) {
?>
<option value="<?= $row->productnr ?>"><?= $row->naam ?></option>
<?php }
?>
</select>
</div>
<div class="form-group dispWidth fl ml">
<label>Aantal</label>
<input type="text" name=amountCount class="form-control dispWidth" placeholder="Hoeveelheid">
</div>
</form>
What I want is every time I duplicate the div, the select-name has to be unique. 我想要的是每次重复div时,选择名称都必须是唯一的。 Also the name of the last input has to be unique (amountCount).
最后输入的名称也必须是唯一的(amountCount)。 Probably by con-catting the i variable behind them both (productnaam1, productnaam2, amountCount1.).
可能是通过在它们后面都连接i变量(productnaam1,productnaam2,amountCount1。)。 How?!
怎么样?!
childNodes[0]
is the text node that contains the newline and indentation. childNodes[0]
是包含换行符和缩进的文本节点。
Try children[0]
instead. 尝试使用
children[0]
。
Also, tempId
refers to the exact same thing as clone
, so just use clone.children[0].value = i;
另外,
tempId
与clone
完全相同的东西,因此只需使用clone.children[0].value = i;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.