Here's my code for generation of the table. I call it via jQuery and ajax.
echo '<table class="database-items table table-bordered">
<tbody>';
foreach($stmt as $item){
echo '
<tr>
<td>'.$item['title'].'</td>
<td>
<img src="wp-content/themes/twentyeleven-child/'.$item['image_path'].'" alt="">
</td>
<td>'.$item['asin'].'</td>
<td>'.$item['weight'].'</td>
<td>'.$item['dimension'].'</td>
<td>'.$item['category'].'</td>
<td>
<button type="button" class="btn btnDeleteitem" alt="'.$item['asin'].'">
<i class="icon-remove"></i>
</button>
</td>
</tr>';
}
echo '</tbody>
</table>';
And if I click the btnDeleteItem button, I want to remove that row, the values will be based on it's td with $item['asin']
Here's my jquery for btnDeleteItem but I don't know how what to put inside
$('.btnDeleteitem').live('click', function() {
//what to put here?
}
Find the button's closest tr ancestor an remove it
$('.btnDeleteitem').live('click', function() {
$(this).closest('tr').remove();
}
Since .live() was deprecated as of jQuery 1.7 use .on() for event deligation
$(document/* or closest existing ancestor of .btnDeleteitem*/).on('click', '.btnDeleteitem', function() {
$(this).closest('tr').remove();
}
Related
I have usual sql scenario with php (mysqli_fetch_assoc) and create table. I want to hide rows randomly when i click on them. I may also need to delete them from the database at the same time, because this file is calling from another with ajax every 5 sec. and hiding is not enough because after calling the rows appear again.. :) I'm no sure that this is the best solution but I'm learning now.
I'm trying something like this it's working, but i can hide only last row. I want hide every row randomly :)
jQuery().ready(function(){
$( "#trow" ).click(function() {
$( "#trow" ).hide()
});
});
<?php while ($row = mysqli_fetch_assoc($result_down)):
$datetime = $row['datetime'];
$device = $row['host'];
$message = $row['msg'];
?>
<tbody>
<tr id="trow">
<td id="device"><?php echo $datetime;?></td>
<td id="datatime"><?php echo $device;?></td>
< td id="message"><?php echo $message;?></td>
</tr>
</tbody>
<?php endwhile;?>
Try to change the trow from an id to a class name
<tbody>
<tr class="trow">
<td id="device"><?php echo $datetime;?></td>
<td id="datatime"><?php echo $device;?></td>
<td id="message"><?php echo $message;?></td>
</tr>
And in the JQuery side, call the click event on the class and not the id this time. The $(this) means the clicked element.
jQuery().ready(function(){
$( ".trow" ).click(function() {
$( this ).hide()
});
});
Simply hiding rows after a click can be done like this:
(function () {
$('table tr').click(function() {
$(this).hide();
});
})();
In my view the form as
<table width="90%" border="0" cellspacing="2" cellpadding="2" id="table-data" align="center" style="border:1px dashed #CCCCCC" class="table table-vcenter table-striped">
<tr class="tr_clone">
<td> % Completion</td>
<td> <?php echo $form->textField($model_result,'floatPaymentpercentage[]',array('class'=>'form-control','placeholder'=>'%')); ?></td>
<td> <?php echo $form->textField($model_result,'varAmount[]',array('class'=>'form-control','placeholder'=>'Amount')); ?></td>
<td><input type="button" name="add" value="Add" class="tr_clone_add btn btn-xs btn-warning"></td>
</tr>
Here i have two textboxes for payment terms..if i save ones it will be saved.
If i add more the last will not saved in database
In my controller we can use print_r()
echo ("<pre>"); print_r($_POST); echo ("</pre>");exit;
The default text field values only shown here.
Here the text fields are added dynamically.
The dynamic added text field's values are not displayed.
In my model the rules are
public function rules()
{
return array(
array('floatPaymentpercentage','required'),
array('varAmount','required'),
);
}
here is the java script for add more
<script type="text/javascript">
$(document).on('click','.delete',function(){
$(this).closest('tr').remove();
});
$("input.tr_clone_add").live('click', function() {
if($(this).val() == "Add")
{
var $tr = $(this).closest('.tr_clone');
var $clone = $tr.clone();
$clone.find(':text').val('');
$tr.find('.tr_clone_add').val('Delete')// set value to Delet
$tr.find('.tr_clone_add').val('Delete')// set value to Delet
.toggleClass('tr_clone_add delete')// toggle classes
.unbind('click'); // unbind the current events from button
$tr.after($clone);
}
else
{
$(this).closest('tr').remove();
}
});
</script>
Please help me to fix this.
Here i can add js for funuction add more
Thanks
I have an html table, and on each row, i would like to add a delete button.
When the user clicks on it, I would like to do two things:
1) remove the row from the table.
2) extract data from the row that was removed - a particular cell, and then make an ajax call using this value to a function that will remove the record from the database. The function returns a fresh list of items, which i will then use to redisplay the same table.
I found the following post from someone else on stackoverflow:
How to remove current row from table in jQuery?
So I guess that addresses point number one. But I don't know how to modify the code in the selected answer of the post to allow for grabbing the id value in the row, and then making an ajax call.
<table class="table table-bordered table-striped" id="databaserecords">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Status</th>
<th>Voice</th>
<th>Jumbo</th>
<th>Mode</th>
<th> </th>
</tr>
</thead>
<tbody>
<?php foreach ($dblist as $record): ?>
<tr>
<td class ='recordId'><?php echo $record['Id'] ?></td>
<td class ='recordName'><?php echo $record['Name'] ?></td>
<td><?php echo $record['Status'] ?></td>
<td><?php echo $record['Voice'] ?></td>
<td><?php echo $record['Jumbo'] ?></td>
<td class='recordmode'><?php echo $record['Mode'] ?></td>
<td><button id="deleteRecord">Delete Record</button></td>
</tr>
<?php endforeach ?>
<script>
$('#deleteRecord').live('click', function() {
//get a count of all records. only allowed to delete if you have more than one record.
var recCount = $('#databaserecords tbody tr').length;
if (recCount > 1)
{
$thevalueIwanttoSave = $(this).closest('recordId').val();
alert($thevalueIwanttoSave);
}
});
</script>
Right now, the alert always says that my variable is undefined.
Can you point me in the right direction? I do know how to code an ajax call... I think I just need help with grabbing the value from the table.
Thanks.
You selector is not correct.
$thevalueIwanttoSave = $(this).parent().siblings('.recordId').text();
closest selects the closest parent of the element(recordId is not parent/grandparent or.. of your button element) and you have also missed a . for class selector. val is used for getting/setting values of form elements, for td elements you should use text or html method. Also note that IDs must be unique(you can use classes instead) and live method is deprecated, you can use on method.
$('#databaserecords').on('click', '.deleteRecord', function() {
var recCount = $('#databaserecords tbody tr').length;
if (recCount > 1) {
var text = $(this).parent().siblings('.recordId').text();
alert(text);
// $(this).closest('tr').remove()
}
});
siblings()
parent()
closest()
text()
on()
$thevalueIwanttoSave = $(this).parent('tr').find('.recordId').text();
it should be .recordId, not recordId
$thevalueIwanttoSave = $(this).closest('.recordId').val();
alert($thevalueIwanttoSave);
Add the ID in an attribute on your delete button and you can just get it via jQuery.
in your php loop:
<button class="deleteRecord" recordID="<?php echo $record['Id'] ?>">Delete Record</button>
in JQuery on
$(".deleteRecord").click(function() {
var id = $(this).attr("recordID");
...
});
You need to use a . to select the element with class recordId. Also use text() to get the value:
$thevalueIwanttoSave = $(this).siblings('.recordId').text();
alert($thevalueIwanttoSave);
I wrote this up quickly because I am having problems with it. I apologize if the code looks messy. Is tbody not clickable? There is no alert, and I don't see any obvious errors
relevant php
echo '<table>';
while ($row = mysql_fetch_array($result)) {
echo
'<tbody class = "reserveAPickupAppointmentRoommateAppointment"
id = "reserveAPickupAppointmentRoommateAppointment">
<tr>
<td>'
.$row["name"].
'</td>
<td>
<span class = "reserveAPickupAppointmentLocaton"
id="reserveAPickupAppointmentLocaton">'
.$row["location"].
'</span>
</td>
<td>
<span class = "reserveAPickupAppointmentSubLocaton"
id="reserveAPickupAppointmentSubLocaton">'
.$row["subLocation"].
'</span>
</td>
</tr>
<tr>
<td>
<span class = "reserveAPickupAppointmentStartTime"
id="reserveAPickupAppointmentStartTime">'
.$row["startTime"].
'</span> -
<span class = "reserveAPickupAppointmentEndTime"
id="reserveAPickupAppointmentEndTime">'
.$row["endTime"].
'</span>
</td>
<td>
<span class = "reserveAPickupAppointmentDate"
id="reserveAPickupAppointmentDate">'
.$row["date"].
'</span>
</td>
</tr>
</tbody>';
}
echo '</table>';
jquery included in my document ready functon
$("#reserveAPickupAppointmentRoommateAppointment").click (function() {
alert ("TEST");
});
The fact that your ID matches your class frightens be a bit. I don't know php, but it seems from the while that you're creating more than one tbody in a loop.
This means that you'd have more than one element with the ID reserveAPickupAppointmentRoommateAppointment. If so it is invalid, and very likely that only the first one will be matched by the selector.
To answer your question directly, yes a tbody can have a handler` as long as you allow the event to bubble up to it.
http://jsfiddle.net/hEw54/
Not knowing the rest of your code, I'd guess that you want the ID on the table, and then to select all tbody elements below it.
$(document).ready(function() {
$('#reserveAPickupAppointmentRoommateAppointment tbody').click(function() {
alert ("TEST");
});
});
Or you could just select directly by class:
$(function() {
$('.reserveAPickupAppointmentRoommateAppointment').click(function() {
alert ("TEST");
});
});
I updated the code above to be placed in a jQuery DOM ready handler. You'll notice that the two examples are slightly different. They're essentially identical, the second being a shortcut for the first. There are other minor differences, but nothing to be concerned with here.
Also note that some people mistake the following for DOM ready code:
(function() {
// I'm not a DOM ready construct
})();
you can't use onclick with a TABLE, TBODY or a TR, but you can attach it to the TD with the jQuery child selector
i have an table
<table class="oldService">
<thead>
<th>name</th>
<th>age</th>
<th>action</th>
</thead>
<tbody>
<?php foreach($array as $k=>$v){ ?>
<tr>
<td><?php echo $k[name] ?></td>
<td><?php echo $k[age]?></td>
<td id="<?php $k[id]" class="delme">X</td>
</tr>
<?php } ?>
</tbody>
<table>
now i want to delete any row by clicking on X of each row except first and last row,
and also need to confirm before deletion.
i used below jquery
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('table.oldService>tbody tr').not(':first').not(':last').click(function(){
if(confirm('want to delete!')){
jQuery(jQuery(this).addClass('del').fadeTo(400, 0, function() {
jQuery(this).remove()}));
jQuery.get('deleteService.php', {id:jQuery(this).attr('id')});
}
else return false;});
});
</script>
this is working perfect,but it execute by click on that row( means any td), i want that this event only occour when user click on X(third td) .
please suggest me how to modify this jquery so that the event occur on click of X.
UPDATE:
i want that minimum one row should be in tbody,
means if there is only one row then no function to delete that row, and if there is many rows then any row he can delete but not the all rows.
You can do this with a bit less code like this:
jQuery('table.oldService').delegate('td.delme', 'click', function() {
if(jQuery(this).parent().siblings(":not(.del)").length === 0) return;
if(!confirm('want to delete!')) return;
jQuery.get('deleteService.php', { id:this.id });
jQuery(this).parent().addClass('del').fadeTo(400, 0, function() {
jQuery(this).remove();
});
});
This attaches one event handler for the table instead of 1 per <td>. First we check if there are any siblings left that aren't deleted (prevent last deletion). Then check if they confirm, then delete the row.
You also need a few html fixes based on the posted question. The last tag needs to be </table> instead of <table>, and those <td> elements in the <thead> need to be wrapped in <tr></tr>. Let me know if you have any trouble, you can see a working demo of this here.
I didn't implement all your animation and AJAX logic, but here is how you could do this in general:
$(function() {
$('table.oldService td.delme:not(:first):not(:last)').click(function() {
$(this).closest('tr').remove();
});
});
Also, I highly recommend you run your code through JSLint. The code sample you posted has a massive number of errors in it.
Try this :
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('table.oldService>tbody tr img.delete').not(':first').not(':last').click(function () {
if(confirm('want to delete!'))
{
jQuery(jQuery(this).addClass('del').fadeTo(400, 0, function() {
jQuery(this).parent().parent().remove()}));
jQuery.get('deleteService.php', {id:jQuery(this).attr('id')});
}
else return false;});
});
</script>
html :
<table class="oldService">
<thead>
<th>name</th>
<th>age</th>
<th>action</th>
</thead>
<tbody>
<?php foreach($array as $k=>$v){ ?>
<tr>
<td><?php echo $v['name'] ?></td>
<td><?php echo $v['age']?></td>
<td><img id="<?php echo $v['id']?>" class="delete" src="del.gif" /></td>
</tr>
<?php } ?>
</tbody>
<table>