James Brooks James Brooks - 2 months ago 7
jQuery Question

Hiding a dynamically created table row on click

I'm currently trying to hide a dynamically created table row after a button has been pressed. So far I have managed to handle part of the dynamic functions.

Each dynamic row has a "Cancel" and "Save" button, I have managed to respond to these with ease. My problem is actually working with the row itself.

$(function() {
$(".add").click(function(){
// Just append to the table
$("table#bookmarks tr:first").after("<tr class='new' id='<?php echo rand(1, 9999); ?>'><td></td><td><b>URL:</b> <input type='text' id='newURL' /><br /><b>Title:</b> <input type='text' id='newTitle' /><br /><b>Description:</b><br /><textarea id='newDesc'></textarea></td><td><b>Tags:</b> <input type='text' id='newTags' /></td><td><a href='#' class='save'>Save</a><br /><a href='#' class='cancel'>Cancel</a></td></tr>");
$('span#links').html('<i style="color: #FF0000">You must reload to recount links!</i>');
// Actually, the user doesn't want to add another link
$('.cancel').click(function() {
$(this).parents(".new").animate({ backgroundColor: "#FF0000" }, "fast").animate({ opacity: "hide" }, "slow");
});
// Seems the user wants to add a link!
$('.save').click(function() {
$("table#bookmarks tr.new #id").animate({ backgroundColor: "#FFFFFF" }, "fast").animate({ opacity: "hide" }, "slow");
});
});

});


I need to now hide the row, I have tried all sorts of various methods, .parent, .attr to name a few.

Answer

Try chaining your jQuery functions like this:

$(function() {
    $(".add").click(function() {
    	$("<tr class='new'><td></td><td><b>URL:</b> <input type='text' id='newURL' /><br /><b>Title:</b> <input type='text' id='newTitle' /><br /><b>Description:</b><br /><textarea id='newDesc'></textarea></td><td><b>Tags:</b> <input type='text' id='newTags' /></td></tr>")
    		.append($("<td></td>")
    			.append($("<a href='#'>Save</a><br/>")
    				.click(function() { $(this).parents(".new").animate({ backgroundColor: "#FF0000" }, "fast").animate({ opacity: "hide" }, "slow"); }))
    			.append($("<a href='#'>Cancel</a>")
    				.click(function() { $(this).parents(".new").animate({ backgroundColor: "#FF0000" }, "fast").animate({ opacity: "hide" }, "slow"); })))
    		.insertAfter($("table#bookmarks tr:first"));
    		$('span#links').html('<i style="color: #FF0000">You must reload to recount links!</i>');
    });
});

(This is a modified version of your original code so it's still a bit messy.)

Comments