Vivek Dragon
Vivek Dragon

Reputation: 2248

Positioning Dynamically created Button

I have created four text boxes and when I click a delete button it adds another set of text boxes with a remove button like this:

Image

This is My script

$(document).ready(function() {
    $("#add").click(function () {
        $('.main').append("<div><br />" + $('.append_list').html() + '<button class="rmv_btn" onclick="$(this.parentNode).remove()">Remove</button></div>');
    });
});

How can I add this button next to the first text box which is created dynamically?

With reference to this Question

Output Image

enter image description here

Upvotes: 0

Views: 162

Answers (3)

Anujith
Anujith

Reputation: 9370

See this : http://jsfiddle.net/MpEUZ/5/

$(document).ready(function() {
$("#add").click(function() {
    $('.main > :first-child').clone().appendTo('.main').find('input[type=text]').val('');
    $('.main .append_list:last').find('input[type=text]:first').after("<button class='rmv_btn' style='clear:both'> Remove </button>");

});
$('.main').on("click", ".rmv_btn", function() {
    $(this).parent().remove();
});
});​

Upvotes: 1

Thijs Kramer
Thijs Kramer

Reputation: 1117

Create a temporary container in which you insert your cloned input list. Then find the first input in that temp container:

$(document).ready(function() {
    $("#add").click(function () {
        var container = $('<div />').addClass('justadded').appendTo('.main');
        $(container).append($('.append_list').html());
        var input = $(container).find('input:first');
        $('<button />').text("Remove").addClass('rmv_btn').attr('onclick', '$(this.parentNode).remove()').insertAfter(input);
        $(container).removeClass('justadded');
    });
});

Upvotes: 1

Magus
Magus

Reputation: 15104

This one should works :

$(document).ready(function() {
    $("#add").click(function () {
        var html = $($('.append_list').html());
        html.find('input').first().after('<button class="rmv_btn" onclick="$(this.parentNode).remove()">Remove</button></div>');

        $('.main').append("<div><br />" + html);
    });
});

I guess $('.append_list') is containing the good html for the inputs.

Upvotes: 0

Related Questions