Search code examples
javascriptjqueryinsertafter

Insert After Last Item by jQuery


This is my all script, I know this is long, but just one line is important and I add all it for insurance:

//Add new Addable div
$('.AddNewE').click(function () {

    var RemoveAddableButton = $('<input type="button" class="RemoveE button red" value="remove" />');

    $(RemoveAddableButton).click(function () {
        $(this).closest('.Addable').remove();
    });


    var TargetId = $(this).attr('id');
    TargetId = TargetId.substring(3);
    var Target = $('.Addable#' + TargetId + ':first');
    var Count = $('.Addable#' + TargetId).size();
    var CloneTarget = $(Target).clone();
    CloneTarget.find('input').val('');
    CloneTarget.insertAfter('.Addable#' + TargetId + ':last'); // ***importantOne
    var TargetName = $(Target).find('input').attr('name');


    if (Count == 1) {

        var CloneName = TargetName + '[1]';
        TargetName = TargetName + '[0]';

        $(Target).find('input').attr('name', TargetName);
        $(Target).find('span[class*="field-validation"]').attr('data-valmsg-for', TargetName);
        $(CloneTarget).find('input').attr('name', CloneName);
        $(CloneTarget).append($(RemoveAddableButton));

        if ($(CloneTarget).find('span[class*="field-validation"]').size() > 0) {
            $(CloneTarget).find('span[class*="field-validation"]').remove();
            $(CloneTarget).append(
                        $('<span class="field-validation-valid invalid-side-note" data-valmsg-replace="true" data-valmsg-for="' + CloneName + '"></span>')
            );
        }


    } else {

        var indx = TargetName.length - 3;
        var CloneTargetName = TargetName.substring(0, indx);
        CloneTargetName = CloneTargetName + '[' + Count + ']';
        $(CloneTarget).find('input').attr('name', CloneTargetName);
        $(CloneTarget).append($(RemoveAddableButton));

        if ($(CloneTarget).find('span[class*="field-validation"]').size() > 0) {

            $(CloneTarget).find('span[class*="field-validation"]').remove();
            $(CloneTarget).append(
                        $('<span class="field-validation-valid invalid-side-note" data-valmsg-replace="true" data-valmsg-for="' + CloneTargetName + '"></span>')
            );

        }

    }



    (function ($) {
        $.fn.updateValidation = function () {
            var form = this.closest("form").removeData("validator").removeData("unobtrusiveValidation");
            $.validator.unobtrusive.parse(form);
            return this;
        };
    })(jQuery);

    $(Target).updateValidation();
    $(CloneTarget).updateValidation();



});

If I click the .AddNewE button then a new div added, but as my script I want to add this new div to the end of the divs so I use

CloneTarget.insertAfter('.Addable#' + TargetId + ':last');

but always the new div added as a second div it means always the :first and :last div is same and is first one also I checked by:

$('.Addable#' + TargetId).css('border', '');
    $('.Addable#' + TargetId + ':last').css('border', '3px dotted green');
    $('.Addable#' + TargetId + ':first').css('border', '3px dotted red');

So where is the problem? why the jQuery can't recognize last div ?


Solution

  • The problem is in the jQuery selector: $('.Addable#' + TargetId + ':last')

    It is not valid HTML when you have multiple elements with the same id (#TargetId). ID is unique and you're not supposed to have more than 1 element with the same ID.

    The jQuery selector assumes you use valid correct HTML markups, so it doesn't bother to collect all your elements with that ID. As soon as jQuery found the first element in the DOM with that ID, it stops and appends your new element right after that.

    Try updating your jQuery selectors to simply: $('.Addable:first') and $('.Addable:last') and see if it works.