NewUser
NewUser

Reputation: 13323

jQuery chosen not working for cloned row

Here's my HTML:

<table>
        <tr>
            <th>Names</th>
            <th>Product Names</th>
        </tr>
        <tr class="data-wrapper">
            <td>
                <select class="form-control required chosen-select-width name" name="source_language[][0]" aria-required="true">
                    <option value="name1">Name 1</option>
                    <option value="name2">Name 2</option>
                    <option value="name3">Name 3</option>
                    <option value="name4">Name 4</option>
                    <option value="name5">Name 5</option>
                </select>
            </td>
            <td><input type="text" name="product-names"></td>
        </tr>
    </table>
    <button type="button" class="btn add-new-data"> Add </button>

Here I have used the jQuery chosen plugin for the drop down. I am cloning the row. However, after cloning the chosen select is not working. Here is my code on jsFiddle.

How can I make chosen work for the cloned elements?

Upvotes: 3

Views: 3648

Answers (1)

Claudio Redi
Claudio Redi

Reputation: 68440

You should clone first and apply chosen later so the cloned element is "chosen free".

jQuery(function($){ 
    var clone = $("table tr.data-wrapper:first").clone(true);
    $('select.name').chosen({width: "100%"});
    $('body').on('click', '.add-new-data', function() {
        var ParentRow = $("table tr.data-wrapper").last();
        clone.clone(true).insertAfter(ParentRow);
        $('tr.data-wrapper:last select').chosen();
    });
});

DEMO

Upvotes: 13

Related Questions