-1

My default view is this. enter image description here

Add button is working as expected but when I try to remove the cloned div I am only able to remove the last one but not all the cloned div one by one from last expect the default one.

Here is my Div and Jquery to add and remove div.

Add:

 $("#AddSubService").click(function(){
                    $("#SubServices").append($('#SubServiceName').clone(true).find("input").val("").end());
                    $("#SubServices").append($('#SubServiceDescription').clone(true).find("input").val("").end());
                });

Remove:

$("#RemoveSubService").click(function(e){                           
                    $("#SubServices").children("div[id=SubServiceDescription]:last").fadeOut();
                    $("#SubServices").children("div[id=SubServiceName]:last").fadeOut();                    
                });

Div:

<div id="SubServices">
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <h2>Sub Services</h2>
                    <input type="button" value="Add" class="btn btn-default" id="AddSubService" /> |
                    <input type="button" value="Remove" class="btn btn-default" id="RemoveSubService" />
                </div>
            </div>

            <div class="form-group" id="SubServiceName">
                @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group" id="SubServiceDescription">
                @Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>

As I am pretty new in MVC and Jquery so any right direction to achieve the same would be highly appreciable.

Jyotish Singh
  • 2,065
  • 3
  • 20
  • 28
  • `.fadeout()` just hides the element (it does not remove it) so your `:last` selector just selects the same one over and over - use `.remove()` instead You also need to remove the `id` attribute (its invalid html) - use a class name instead –  Oct 26 '16 at 05:59
  • As a side note - your code will not bind to your model because of the duplicate `name` attributes - refer [this answer](http://stackoverflow.com/questions/28019793/submit-same-partial-view-called-multiple-times-data-to-controller/28081308#28081308) for options to implement dynamically adding and removing collection items –  Oct 26 '16 at 06:04
  • Remove is working as expected but It's also remove the default one so how to prevent that from happening? – Jyotish Singh Oct 26 '16 at 06:11
  • Your 'default' one should just be a 'template' (inside a hidden element that gets cloned) so it can never be removed. But you can always use `.length` first and only remove the last one if length > 1. But as I noted previously, you implementation will never work, and there is no point including `ValidationMessageFor()` since that wont work either. You need to abandon this and read the link in my previous comment –  Oct 26 '16 at 06:19
  • Jigar7521 is right, after calling clone() you should change its id attribute, may calling attr('id', new-id); Maybe it doesn't resolve your issue but it is the way it needs to be. If you want to prevent default to be removed, you could use :not() selector (https://api.jquery.com/not-selector/) e.g.: $( "input:not(:checked) + span" ).css( "background-color", "yellow" ); – Marco Oct 26 '16 at 13:03

3 Answers3

2

Use below script function to remove cloned divs

        $("#RemoveSubService").click(function (e) {
            var divCount = $("#SubServices").children("div[id=SubServiceDescription]").length;
            while (divCount > 1) // comparing with 1 beacuse: It will keep default div and remove rest
            {
                $("#SubServices").children("div[id=SubServiceDescription]:last").remove();
                $("#SubServices").children("div[id=SubServiceName]:last").remove();
                divCount--;
            }
        });
Suyog
  • 171
  • 7
  • I believe you should use If condition instead of while in order to remove clone div one by one otherwise It will remove all the cloned div in single click. – Jyotish Singh Oct 27 '16 at 08:54
1

This is not happening correct because of id attribute, id attribute should always be unique in html that'w why, use class instead of.

Jigar7521
  • 1,549
  • 14
  • 27
  • Your correct in saying `id` attributes should be unique, but it has nothing to do with OP's issue. –  Oct 26 '16 at 22:25
  • Well, you can do that, you even can use class instead of id, let me know if you want then i can make demo for you just like as per your requirement – Jigar7521 Oct 27 '16 at 04:05
0

  $(document).ready(function() {
    $('.AddNew').click(function() {
  $(".TargetElements:first").clone().insertAfter('.TargetElements:last');
      $('.Remove').show();
    });
  }); 
  
   

$(document).ready(function () {
            $('.Remove').click(function () {
                if ($(".TargetElements").length > 1) {
                    $(".TargetElements:last").remove();
                }
                else {
                    $('.Remove').hide();
                }
            });
        });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="TargetElements">
  <label>Name</label> </div>
<div>
  <input type="button" value="Add" class="AddNew" />
  <input type="button" value="Remove" class="Remove" hidden="hidden" />
</div>
      <div class="TargetElements">
                         <label>Name</label>
                         </div>

  <div> <input type="button" value="Add New Language" class="AddNew" />

                        <input type="button" value="Remove" class="Remove" hidden="hidden" />
                        </div>

     <script>
            $(document).ready(function () {
                $('.AddNew').click(function () {
                    $(".TargetElements:first").clone().insertAfter('.TargetElements:last');
                    $('.Remove').show();
                });
            });
        </script>

        <script>
            $(document).ready(function () {
                $('.Remove').click(function () {
                    if ($(".TargetElements").length > 1) {
                        $(".TargetElements:last").remove();
                    }
                    else {
                        $('.Remove').hide();
                    }
                });
            });
        </script>
Amal Sebastian
  • 193
  • 3
  • 19