JQuery add row to table and bind event to last only

I am trying to add a copy of the selected menu to the bottom of the table when the selection is made in the last select menu in the list. At this point, I would like to apply the behavior to the last select menu in the table. The code below adds a row to the table, but fails to undo the action successfully, and as a result, the first select menu continues to show the behavior even after the action has been disabled.

JavaScript:

var selectRow;
$(document).ready(function() {
    selectRow = $('#selectWrapper').html();
    rebindLastSelectBox();  
});

function rebindLastSelectBox() {
    $('#selectList:last').change(function(e) {          
                $(this).unbind('change');
        $('table').append("<tr id='selectWrapper'>" + selectRow + "</tr>");
                rebindLastSelectBox();
   });
};

      

HTML:

<head>
    <title>JS Test</title>
    <script src="./js/jquery.js" type="text/javascript" charset="utf-8"></script>
    <script src="./js/application.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>

<table>
    <tr>
        <td>Title</td><td><input type="text" name="some_name" value="" id="some_name"></td>
    </tr>
    <tr id='selectWrapper'> 
        <td>Items</td><td><select name="items[]" id="selectList" size="1">
            <option value="1">Item 1</option>
            <option value="2">Item 2</option>
        </select></td>
    </tr>
</table>
</body>

      

All suggestions are gratefully received!

Adam

+2


source to share


1 answer


To get you working, just change the id to classes on tr and select. Js could be improved, but lets you get the job done first.



<head>
    <title>JS Test</title>
    <script src="./js/jquery.js" type="text/javascript" charset="utf-8"></script>
    <script src="./js/application.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>

<table>
    <tr>
        <td>Title</td><td><input type="text" name="some_name" value="" id="some_name"></td>
    </tr>
    <tr class='selectWrapper'>     
        <td>Items</td><td><select name="items[]" class="selectList" size="1">
                <option value="1">Item 1</option>
                <option value="2">Item 2</option>
        </select></td>
    </tr>
</table>
</body>

var selectRow;
$(document).ready(function() {
    selectRow = $('tr.selectWrapper').html();
    rebindLastSelectBox();  
});

function rebindLastSelectBox() {
    $('select.selectList:last').change(function(e) {                  
        $(this).unbind('change');
        $('table').append("<tr class='selectWrapper'>" + selectRow + "</tr>");
        rebindLastSelectBox();
   });
};

      

+3


source







All Articles