Reputation: 871
I have somehow managed to Code a working system to delete a row from a Table retrieved from Database.
There is a problem with my code which i couldnt correct
Jquery function to delete and slide up the row
<script type="text/javascript">
$('document').ready(function() {
$('a').click(function() {
if (confirm("Are you sure?")) {
var del_id = $(this).attr('id');
var parent = $(this).parent().parent();
$.post('delete.php', {id:del_id},function(data){
parent.slideUp('slow', function() {
$(this).remove();
});
});
}
return false;
});
});
</script>
Below is the PHP code for the Retrieved Table
<?php
while(($row = mysqli_fetch_assoc($result))) {
echo "<tr>";
echo "
<td>
<span class='label label-red'>".$row['lid']."</span>
</td>
<td>
".$row['name']."
</td>
<td>
<a href='#'>".$row['email']."</a>
</td>
<td>
".$row['tel']."
</td>
<td>
Mental Stress Relief
</td>
<td>
<a href=\"javascript:return(0);\" id=".$row['lid'].">Delete</a>
</td>
";
}
?>
Everythings working fine.
But the Navigation Menu uses the same <a>
tag, So when I click the navigation link from this page .. its slides up just as the table row. I couldnt navigate... Should i Use ID or something??
<ul class="navigation">
<li><a href="dashboard.php" class="blblue">Statistics</a></li>
<li><a href="leads.php" class="blyellow">Lead Detials</a></li>
<li><a href="includes/logout.php" class="blred">Logout</a></li>
</ul>
I am confused. What to do?
Upvotes: 2
Views: 196
Reputation: 93581
Use a class to identify the various types of link. e.g. class="delete"
and change your code to target that:
$(function () {
$('a.delete').click(function () {
if (confirm("Are you sure?")) {
var del_id = $(this).attr('id');
var $tr = $(this).closest('tr');
$.post('delete.php', {
id: del_id
}, function (data) {
$tr.slideUp('slow', function () {
$(this).remove();
});
});
}
return false;
});
});
PHP changed to:
<td>
<a href="#" class="delete" id=".$row['lid'].">Delete</a>
</td>
Notes:
$(function(){...});
delete
class to any "delete links" (obviously not to any other links). Classes can be used to imply specific behavior on elements (from a jQuery perspective). When there are multiple elements you should avoid using ID, or partial-ID, selectors.parent().parent()
is "fragile coding" and does not cope with HTML changes, so target a specific ancestor element with closest()
instead (e.g. the closest("tr")
)parent
to the more meaningful $tr
in the example, as I assume it is the row you remove.$
prevfix for jQuery object variables, for readability.href=\"javascript:return(0);\"
in your link. Change it to a simple #
bookmark link.Upvotes: 1
Reputation: 683
Change below line form :
$('a').click(function(){
to
$('td a').click(function(){
Upvotes: 1