Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 785
Emidee Avatar asked Feb 17 '26 02:02

Emidee


2 Answers

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 );
});
like image 143
Joseph Marikle Avatar answered Feb 19 '26 14:02

Joseph Marikle


Try this with using the select elements selectedIndex

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

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

    var index = $('select', $btn.closest('tr')).prop('selectedIndex');

    $('select', $clonedRow).prop('selectedIndex', index);

    $btn.closest('tbody').append( $clonedRow );
});
like image 43
Naftali Avatar answered Feb 19 '26 15:02

Naftali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!