Search code examples
jqueryjquery-selectorsclonefield

Clone a row containing selects, and clone selects' values


I have this HTML:

<tr>
    <td>
        <input type="hidden" name="MatchId[]" value="">
        <select name="TeamId[]">
            <optgroup label="Women">
                <option value="18">Women 1</option>
                <option value="17">Women 2</option>
            </optgroup>
            <optgroup label="Men">
                <option value="9">Men 1</option>
                <option value="8">Men 2</option>
            </optgroup>
        </select>
    </td>
    <td>
        <select name="Day[]">
            <!-- blah -->
        </select>
    </td>
    <td>
        <input class="addButton" type="button" value="+">
    </td>
    <td>
        <input class="removeButton" type="button" value="-">
    </td>
</tr>

I would like to clone the row when I click on the + button, but also set the value of the <select> to be the same as the original row.

For now, I have this code, which successfully clones the row, but leaves the new <select> fields with the first value as a selection:

$('.addButton').livequery('click', function()
{
    var $btn = $(this);

    var $clonedRow = $btn.closest('tr').clone();

    $btn.closest('tbody').append( $clonedRow );
});

How could I do that?

Edit: subsidiary question: how could I set the focus on the first field of the cloned row after I click on the + button?


Solution

  • You can do it manually:

    http://jsfiddle.net/Tp7hg/

    $('.addButton').live('click', function()
    {
        var $btn = $(this);
        var $row = $btn.closest('tr')
    
        var $clonedRow = $row.clone();
        $clonedRow.find("select").each(function(i){
            this.selectedIndex = $row.find("select")[i].selectedIndex;
        })
    
        $btn.closest('tbody').append( $clonedRow );
    });