Andrew .Nic
Andrew .Nic

Reputation: 53

Fix Add / Remove Input Field

I have the code below to add or remove input fields dynamically.

    $(document).ready(function() {
        $(".add-more").click(function(){
            var html = $(".copy").html();
            $(".after-add-more").after(html);
        });

        $("body").on("click",".remove",function(){
            $(this).parents(".col-md-6").remove();
        });

    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css" rel="stylesheet"/>


<div class="row after-add-more">

    <div class="col-md-6">
        <div class="form-group">
            <div class="input-group">
                <input type="text" class="form-control required" name="Categories[]" placeholder="Add Text">
                <span class="input-group-btn"><button class="btn btn-success add-more" type="button">ADD</button></span>
            </div>
        </div>
    </div>

</div>

<div class="copy hide">
    <div class="row">

        <div class="col-md-6">
            <div class="form-group">
                <div class="input-group">
                    <input type="text" class="form-control required" name="Categories[]" placeholder="Add Text">
                    <span class="input-group-btn"><button class="btn btn-danger remove" type="button">REMOVE</button></span>
                </div>
            </div>
        </div>

    </div>
</div>

Now the problem is when you click on 'Add' button, the next inputs will be created upto the previous field.

enter image description here

How can I fix my code. I need to sort input fields Up to Down.

Upvotes: 2

Views: 141

Answers (1)

Faseeh Haris
Faseeh Haris

Reputation: 669

Please use append instead of after in your code.

$(document).ready(function() {
        $(".add-more").click(function(){
            var html = $(".copy").html();
            $(".after-add-more").append(html);
        });

        $("body").on("click",".remove",function(){
            $(this).parents(".col-md-6").remove();
        });

    });

Upvotes: 3

Related Questions