views:

258

answers:

1

Hi all, I am trying to append a copy of a select menu to the bottom of a table when a selection is made in the last select menu in the list. At this point I'd only like to apply the behaviour to the last select menu in the table. The code below adds in the row to the table but fails to unbind the action successfully, and as a result the first select menu continues to show the behaviour, even after the action has been unbound.

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 gratefully recieved!

Adam

+3  A: 

To get you working just change the id's to classes on the tr and the select. The js can be improved however lets get you working 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();
   });
};
redsquare
Thanks for the pointer on changing to classes rather that IDs. After changing my ids however I can see no dynamic updating of the page. I'd be interested to see how you'd improve the javascript too.Cheers,Adam
Adam
works fo me here http://pastebin.me/f576b606b1bbc67794a9c8e8dcda9330
redsquare