tags:

views:

79

answers:

0

This is some code to allow the user to insert/delete rows. Because focusout occurs before the click event, I have to save which row to be removed until after the new on has been inserted. Q: Am I handling the variable named ROWTOBEREMOVED correctly? It's in all caps for the purpose of this question only.

<!DOCTYPE HTML>
<html>
<head>
<script src="http://www.google.com/jsapi"&gt;&lt;/script&gt;
<script type="text/javascript">
function OnLoad() {
    var ROWTOBEREMOVED = null;

    $('input[name="myid"]').live('focusout', function() {
        var myValue = $(this).val();
        if (myValue == '') {
            ROWTOBEREMOVED = $(this);
        } else {
            $(this).parents("td").empty().append(myValue);
      }
    });
    $('.insert').live('click', function() {
        var currentRow = $(this).parents("tr:first");
        var newRow = currentRow.clone(true);
        newRow.children('td:last').empty().append('<input name="myid" />');
        currentRow.after(newRow);
        if(ROWTOBEREMOVED != null) {
            ROWTOBEREMOVED.parents("tr").remove();
            ROWTOBEREMOVED = null;
        }
        document.myForm.myid.focus();
    });
    $('.delete').live('click', function() {
        if (confirm("Are you sure?")) {
            $(this).parents("tr").remove();
        }
    });
}
google.load("jquery", "1");
google.setOnLoadCallback(OnLoad);
</script>
</head>
<body>
<form name="myForm">
<table border="1">
<tr>
<td class="insert">Add</td>
<td class="delete">Erase</td>
<td>One</td>
</tr>
<tr>
<td class="insert">Add</td>
<td class="delete">Erase</td>
<td>Two</td>
</tr>
<tr>
<td class="insert">Add</td>
<td class="delete">Erase</td>
<td>Three</td>
</tr>
</table>
<input name="Other">

</form>
</body>
</html>