http://www.quirksmode.org/dom/domform.html

我正在尝试在我的项目中实现此扩展表单功能。由于我使用CakePHP命名约定进行编译,因此在我的扩展形式中,我有2个字段名称:
[学生] [0] [年龄]
[学生] [0] [年级]

该脚本不起作用,因为它仅将计数器附加在字段名的末尾,如下所示:fieldName + counter,而我正在尝试增加计数,如下所示:
[学生] [1] [年龄]
[学生] [1] [年级]

[学生] [2] [年龄]
[学生] [2] [年级]

我是Java语言的新手,希望有人可以建议如何解决这个问题。

HTML:

<span id="readroot" style="display: none">
<input class="btn btn-default" type="button" value="Remove review" onclick="this.parentNode.parentNode.removeChild(this.parentNode);" />
<br /><br />
<div class="row">
    <div class="col-lg-3">
        <div class="form-group required"><label for="Student1Age">Age</label><input name="data[Student][0][age]" class="form-control" placeholder="Age" maxlength="11" type="text" id="Student1Age" required="required"/></div>
    </div>
    <div class="col-lg-3">
        <div class="form-group required">
            <label for="Student1Grade">級別</label>
            <select name="data[Student][0][grade]" class="form-control" id="Student1Grade" required="required">
                <option value="">Please Select</option>
                <option value="1">Grade 1</option>
                <option value="2">Grade 2</option>
            </select>
        </div>
    </div>
</div></span>

    <span id="writeroot"></span><input class="btn btn-default" type="button" onclick="moreFields()" value="Give me more fields!" />


Javascript:

    var counter = 0;
function moreFields() {
    counter++;
    var newFields = document.getElementById('readroot').cloneNode(true);
    newFields.id = '';
    newFields.style.display = 'block';
    var newField = newFields.childNodes;
    for (var i=0;i<newField.length;i++) {
        var theName = newField[i].name
        if (theName)
            newField[i].name = theName + counter;
    }
    var insertHere = document.getElementById('writeroot');
    insertHere.parentNode.insertBefore(newFields,insertHere);
}

最佳答案

您必须像下面这样替换这一行。

您的:

newField[i].name = theName + counter;


新的一个:

newField[i].name = "[Student][" + counter + "][" + theName + "]";


我用您的脚本制作了一个工作示例页面。检查以下链接。

http://sugunan.net/demo/extend_form.php

关于javascript - 如何在中间增加输入字段名称,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31903261/

10-11 20:02