tags:

views:

46

answers:

1
+1  Q: 

jQuery Add/Delete

This snippet does what I want it to do with 1 exception. It works correctly if the user presses "Add" over and over again - it removes the empty row and adds the new row. If the user types something into the input field, that field is converted into table data. The only problem I have is when the user presses "Add" twice, and the second "Add" is below the first. It works if the second "Add" is above the first.

I'm sure it has something to do with the fact that I removed the row if the input value was empty.

<!DOCTYPE HTML>
<html>
<head>
<script src="http://www.google.com/jsapi"&gt;&lt;/script&gt;
<script type="text/javascript">
function OnLoad() {
    $('input[name="myid"]').live('focusout', function() {
        var myValue = $(this).val();
        if (myValue == '') {
            $(this).parents("tr").remove();
        } 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);
        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>
+1  A: 

This is happening because blur happens before click, in your code

$(this).parents("tr").remove();

is executing before the click happens, so there's actually nothing to click on (and bubble up to trigger the .live() event). In your case, I would remove the add option from the currently being added row.

Nick Craver
OK, I removed the add option from the currently being added row. But I still have the problem.Since focusout is happening before click, how can I save the identity of the row that I need to remove once click has inserted the new row?
cf_PhillipSenn
I think I got it.Thanks for your direction.
cf_PhillipSenn