使用JavaScript将输入添加到面板时出现问题

时间:2018-09-19 14:06:07

标签: javascript html

我的问题是该按钮在以下面板上停止工作。我想这是个id问题,但我不知道如何解决(我对javascript知之甚少)

HTML:

<div class="card-body">
  <button id="Addpanel">Add panel</button>
</div>

我的脚本:

<script>
    $(function() {
        $('#Addpanel').click(function(){
            var newDiv = $('<div class="panel-default"><br /><div class="form-control"><input type="text" id="fieldnum" name="fieldnum" value="">Fill number<a type="button" id="filldetails" class="btn" onclick="addFields()">Add</a></div><div id="container" class="form-control" />'
            );
            $(".card-body").append(newDiv);
        });
    });
</script>

第二:

<script type='text/javascript'>
    function addFields(){
        var number = document.getElementById("fieldnum").value;
        var container = document.getElementById("container");

        while (container.hasChildNodes()) {
            container.removeChild(container.lastChild);
        }
        for (i=0;i<number;i++){
            var input = document.createElement("input");
            input.type = "text";
            input.name = "input" + (i+1);
            input.className = "form-control";
            container.appendChild(input);
        }
    }
</script>

1 个答案:

答案 0 :(得分:0)

您应该这样使用:

$(function () {
    var count = 0;
    $('#Addpanel').click(function () {
        var newDiv = $('<div class="panel-default"><br /><div class="form-control"><input type="text" id="fieldnum' + count + '" name="fieldnum" value="">Fill number<a type="button" id="filldetails' + count + '" class="btn" onclick="addFields()">Add</a></div><div id="container' + count + '" class="form-control" />');
        $(".card-body").append(newDiv);
        count++;
    });
});