Tuesday, August 26, 2014

arrange the numbers in input name element array after remove one of it by js

I want after add a input and remove it, arrange the numbers in input name element array by jQuery but don't work for me after remove input. How can fix it?

Answer


I guess that you want to re-number the inputs after a remove, so that the array is made of contiguous numbers.
I have rewritten some things, among which the renumbering function, using an index contextual to the parent function.
function removeidx(context, clss, type) {
    var remove = $(context).closest(clss);
    remove.fadeOut('slow', function () {
        $(this).remove();
        var idx = 0;
        $(clss).each(function () {
            var checkBoxes = $('input[type="' + type + '"]', this);
            checkBoxes.each(function () {
                var name = $(this).attr('name');
                name = name.replace(/\d+/, idx);
                $(this).attr('name', name);
                idx = idx + 1;
            });
        });
    });
}

$(document).on('click change', 'a.adding', function (e) {
    e.preventDefault();
    var idx = $('.Row').length;
    $('.ffdd').append('<div class="Row"> <input name="arr[' + idx + '][]" type="text" value=""> <a href="#" class="remove_row" title="remove this row">Remove</a></div>');
});

$('.ffdd').on('click', 'a', function (e) {
    removeidx(this, '.Row', 'text');
})
You can see a working version there : http://jsfiddle.net/8sVWp/

ref 
http://stackoverflow.com/questions/14600150/arrange-the-numbers-in-input-name-element-array-after-remove-one-of-it-by-js

No comments:

MS in Computer Science with paid training in USA company