Pergunta

I'm having an issue with appending an element to a page. What I've got is a drop down list which has been populated by php and I need to duplicate it when the user presses add item. I can get it duplicating well and good but the issue lies in getting it to conform to a table. As I need each list to have it's own unique id I can't just give the row an id and duplicate that however the code I've tried adds an empty row and then the options go in a box underneath. Is there something I'm missing.

$(document).ready(function() 
{
    var InputsWrapper   = $("#input-table"); //Input boxes wrapper ID
    var AddButton       = $("#add-new"); //Add button ID
    var inputId=0; //to keep track of text box added

    $(AddButton).click(function (e)  //on add input button click
    {           
        var original = document.getElementById('listItem' + inputId); //Get the list box to be duplicated
        var clone = original.cloneNode(true); //Clone the original
        clone.id = 'listItem' + ++inputId; //Give the clone a unique id
        InputsWrapper.append("<tr><td>");
        InputsWrapper.append(clone); //Attach clone to parent
        InputsWrapper.append("</td></tr>");
        return false;
    });
});
Foi útil?

Solução

(you forgot to add jQuery library in your fiddle...)

You are adding the <tr> directly to the table, but there's supposed to be a <tbody> tag inbetween. It seems to work fine if you change your jquery selector into this:

var InputsWrapper   = $("#input-table tbody");

Here's a working fiddle

Outras dicas

I tihnk the problem is that your are missing a tbody element.

You can use one stament in jQuery using find, clone, wrapAll and closest.

Code:

$(document).ready(function () {
    var InputsWrapper = $("#input-table"); //Input boxes wrapper ID
    var AddButton = $("#add-new"); //Add button ID
    var inputId = 0; //to keep track of text box added

    $(AddButton).click(function (e) //on add input button click
    {
        $(InputsWrapper).find('tbody:last').append($("#listItem" + inputId).clone(true, true).attr("id", "listItem" + (inputId + 1)).wrapAll("<tr><td>").closest("tr"));

        inputId++; //Give the clone a unique id

        return false;
    });
});

Demo: http://jsfiddle.net/IrvinDominin/h7567/

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top