【问题标题】:Javascript change value of attribute of firstChildJavascript更改firstChild属性的值
【发布时间】:2014-01-03 18:24:38
【问题描述】:

问题: 我正在使用按钮复制 div。 在 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>

我正在使用这个脚本:

<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>

如您所见,我正在尝试更改每个输入的值。 每次复制 div 时添加 1 。 显然它不起作用。我该怎么做?

更新:

所以我已经完成了第一部分。 现在我需要更深入。

<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>

我想要的是每次复制 div 时,选择名称必须是唯一的。最后一个输入的名称也必须是唯一的(amountCount)。 可能通过将 i 变量放在它们后面(productnaam1、productnaam2、amountCount1.)。怎么样?!

【问题讨论】:

    标签: javascript php html forms children


    【解决方案1】:

    childNodes[0] 是包含换行符和缩进的文本节点。

    改用children[0]

    另外,tempId 指的是与clone 完全相同的东西,所以只需使用clone.children[0].value = i;

    【讨论】:

    • 我还有一个问题,它作为更新发布。你能帮帮我吗?
    • 一般来说,当你有多个相同的时候,你应该使用name='something[]'。在服务器端,您将获得$_POST['something'] 作为一个数组。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 2018-11-27
    • 1970-01-01
    相关资源
    最近更新 更多