So I have a table that contains a column with a button. When this button is clicked, it toggles the class of the current table row and then replaces the button.
$(document).ready(function() {
$(".checkOut").click(function() {
var currentRow = $(this).closest("tr");
$(currentRow).removeClass("checkedIn");
$(currentRow).addClass("checkedOut");
$(this).replaceWith('<button title="Check In" class="checkIn" value="true" name="check_in"><img alt="Check In" src="../images/check.png"></button>');
} );
$(".checkIn").click(function() {
var currentRow = $(this).closest("tr");
$(currentRow).removeClass("checkedOut");
$(currentRow).addClass("checkedIn");
$(this).replaceWith('<button title="Check Out" class="checkOut" value="true" name="check_out"><img alt="Check Out" src="../images/minus.png"></button>');
} );
});
The initial click seems to work just fine. However when I click to change the state back to its orignal, it does not seem to work. I think it is a problem with replaceWith. Any help would be most appreciated!
1. You have to use
.live()to attach a handler to the event for all elements which match the current selector, now and in the future.2. You were doing an unnecessary re-constructing of the variable
currentRow. I added a$sign, so you know it’s already a jQuery object, and not to re-construct it.In addition, I added code to cache the
$currentRowand$thisobjects, so you won’t have to lookup the DOM every time you want to manipulate them.