How to fix table row no being clicked after append function? - javascript

I am trying to create a new table row every time the associated button is clicked. However, once I click the button and I go to select the row, it does not get highlighted. I have an append function that passes a <tr> to the html. My end goal is to have the the new row that was appended become clickable and can be selected.
Code:
<div class="col-md-3 left-pane">
<div class="row justify-content-md-center">
<button class="btn btn-sm btn-block eNew">New Tier</button>
</div>
<hr>
<table class="table table-sm table-hover tAdd">
<tbody>
<tr>
<td>IIS</td>
<td><button class="btn btn-sm btnD">Delete</button></td>
</tr>
<tr>
<td>SQL</td>
<td><button class="btn btn-sm btnD">Delete</button></td>
</tr>
<tr>
<td>Windows File Share</td>
<td><button class="btn btn-sm btnD">Delete</button></td>
</tr>
<tr>
<td>Etc</td>
<td><button class="btn btn-sm btnD">Delete</button></td>
</tr>
</tbody>
</table>
</div>
Javascript:
$(".eNew").on("click", function(event){
$(".tAdd tbody").append(
"<tr>" +
"<td>New Selector</td>" +
"<td><button class=\"btn btn-sm btnD\">Delete</button></td>" +
"</tr>"
);
$(".tAdd tr").click(function() {
$(".tAdd tr").removeAttr('class');
$(this).toggleClass("table-active");
});
Also, it works for the original <tr> that is in the html file but for some reason when I append a table row it does not work.

This is entirely due to the fact that dynamic content is not bound using the event handler you have declared:
$(".eNew").on("click", function(event){
Although this will bind to all .eNew elements when the code first runs, new elements will not be bound.
Instead, bind to the document and specify .eNew as a selector for the click event and it will work:
$(document).on("click", ".eNew", function(event){
Edit following OP comment about not working
Just to verify that your code should now look like this:
$(document).on("click", ".eNew", function(event){
$(".tAdd tbody").append(
"<tr>" +
"<td>New Selector</td>" +
"<td><button class=\"btn btn-sm btnD\">Delete</button></td>" +
"</tr>"
);
});
$(document).on("click", ".tAdd tr", function(event){
$(".tAdd tr").removeAttr('class');
$(this).toggleClass("table-active");
});

Related

Can't delete current row of jQuery DataTable using local button

I have a jQuery Datatable and I dynamically add rows. Each row has a cell in which there's a delete button. My problem is that I can't get to delete the rows with the buttons and I can't even manage to target the current row.
Here's my DataTable code :
var tab_presta = $("#tableau_presta").DataTable({
"searching": false,
"paging": false,
"ordering": false,
"info": false,
responsive: true,
"language": {
"emptyTable": "No product added to the contract for the moment."
}
});
Here is how I create the buttons on each row (on a submit event) :
form2.on('submit', function (event) {
tab_presta.row.add(
[
'<center><button type="button" id="btn_supp' + (++idCount) + '" onclick="alert(this.parentNode)" class="btn btn-xs btn-block btn-danger confirmation">Delete</button></center>'
]
)
.draw( false );
// here I dynamically add an id to each button based on a variable
$('.btn btn-xs btn-block btn-danger confirmation').each(function() {
$(this).attr('id', 'suppr' + idCount);
idCount++;
});
});
And here is my code for deleting when clicking on each button :
for (j = 0; j <= btn_count; j++) {
$("#tableau_presta").on("click", btn_supp[j], function(){
//tab_presta.row($(this).parents('tr')).remove().draw(false);
var row = $(this).closest("tr");
console.log(row);
});
}
As you can see I commented the remove() part because it doesn't work, so I tried to find the closest tr of $(this) (button), but I don't get the row in the console as a result. It's empty and I don't understand why because the button actually exists and I can get its id when I click on it if I put a onclick"alert(this.id).
Any idea ?
You don't need to bind the click event inside of a loop. Instead, use a class or an attribute selector. In this case, selecting all elements with an id that ^ starts with btn_supp = [id^=btn_supp].
$("#tableau_presta").on("click", "[id^=btn_supp]", function() {
$(this).closest("tr").remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tableau_presta">
<tr>
<td>
<button type="button" id="btn_supp1" class="btn btn-xs btn-block btn-danger confirmation">Delete</button>
</td>
</tr>
<tr>
<td>
<button type="button" id="btn_supp2" class="btn btn-xs btn-block btn-danger confirmation">Delete</button>
</td>
</tr>
</table>

Getting user from db and appending to element

This might be a simple question but have kept me busy for the best part of a hour.
I have the following script which generates all active reservations, in the table reservations
require("../includes/connect.php");
function dispAllReservations(){
$i= 1;
global $db;
$date = date('Y-m-d');
$sql ="SELECT * FROM
reservations WHERE pickup_date > '$date'";
$statement = $db->prepare($sql);
$statement->execute();
$bookings = $statement->fetchAll();
$statement->closeCursor();
echo'<table cellpadding="0" cellspacing="0" class=
"table-responsive gzblog-table" id="gzhotel-booking-booking-id">
<thead>
<tr>
<th class="date-th">Reservation ID</th>
<th class="title-th">Car Group</th>
<th>Pickup Date</th>
<th>Return Date</th>
<th>Customer</th>
<th>Email</th>
<th>Amount</th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>';
foreach($bookings as $booking){
if($i%2 == 0){
$class = 'odd';
}
else{
$class = 'even';
}
echo' <tr class='.$class.'>';
echo'<td>'.$booking['res_id'].'</td>';
echo'<td>'.$booking['car_group'].'</td>';
echo'<td>'.$booking['pickup_date'].'</td>';
echo'<td>'.$booking['return_date'].'</td>';
echo'<td>'.$booking['renter_name'].'</td>';
echo'<td>'.$booking['email'].'</td>';
echo'<td>AMOUNT HERE</td>';
echo'<td><a class="btn btn-primary btn-sm fancybox" href="#email">
<span class="glyphicon glyphicon-envelope"></span></a>
</td>';
echo'<td><a class="btn btn-success btn-sm">
<span class="glyphicon glyphicon-pencil"></span></a>
</td>';
echo'<td><a class="btn btn-danger btn-sm icon-delete">
<span class="glyphicon glyphicon-trash"></span></a>
</td>';
echo'</tr>';
}//foreach
echo'</tbody>';
echo'</table>';
}//function
The output of the script generates the following
My Problem / Question
When delete button is clicked -- I need to ensure the correct reservation is deleted, same with the edit button, if edit button is clicked I need to ensure the correct user is edited.
What I need to do
I'm guessing I would need to find a way to append the corresponding value for each user in the loop to the element.
I was thinking of a textbox setting display none and then echoing the value inside the value attribute, but that didn't work...
I'm really stuck here any advise would be appreciated
NOTE: All emails are fictional
Try this:
<a class="btn btn-primary btn-sm fancybox" href="#email" onclick="onDelete(your-id)">
<span class="glyphicon glyphicon-trash"></span>
</a>
<a class="btn btn-primary btn-sm fancybox" href="#email" onclick="onEdit(your-id)">
<span class="glyphicon glyphicon-pencil"></span>
</a>
Create this function:
<script>
//Delete function
function onDelete(id){
$.ajax({
// do someting
});
}
// Edit function
function onEdit(id){
$.ajax({
// do someting
});
}
</script>
You did not tell us at all how do you want to edit/delete you reservations, but based on the tags you used you can take this approach...
1) In your PHP script generate data attributes on rows or cells, like this:
<tr data-id="put_reservation_id_here">
2) And then use jQuery to hook actions to various elements in the table:
$('#gzhotel-booking-booking-id').on('click', '.icon-delete', function() {
var reservationId = $(this).closest('tr').data('id');
// now you have reservation ID and do whichever AJAX call with it
});
You can use data attributes in your html and then get the data attribute value using javascript.
Example:
In your button:
<a class="btn btn-danger btn-sm icon-delete" data-id="your_Id"><span class="glyphicon glyphicon-trash"></span></a>
Replace your_Id with the correct id.
Then using javascript on your onClick event:
$(this).data('id');
This will retrieve the id that you need to handle the action.
Hope this helps.

Alert multiple column using javascript

I'm trying to alert fields. Here is my html
<table width="100%" id="example1" class="table table-bordered table-striped">
<tr>
<td> Nip </td>
<td> Nama Lengkap </td>
</tr>
<tr id='ke0'>
<td> <input class="form-control nipnya" type="text" name="nip[]" /> </td>
<td> <input class="form-control namanya" type="text" name="namalengkap[]" /> </td>
</tr>
<tr id='ke1'>
</tr>
</table>
<div>
<a id="add_row" class="btn btn-success pull-left">Tambah Baris Baru</a>
<a id="delete_row" class="pull-left btn btn-danger">Hapus Baris</a>
</div>
and i have this jquery
$(document).ready(function() {
$("#rmnya").change(function() {
$('#td11').html($("#rmnya").val());
});
var i = 1;
$("#add_row").click(function() {
$('#ke' + i).html('<td><input class="form-control nipnya" type="text" name="nip[]" /> </td>' +
'<td> <input class="form-control namanya" type="text" name="namalengkap[]" />' +
'</td>');
$('#example1').append('<tr id="ke' + (i + 1) + '"></tr>');
i++;
});
$("#delete_row").click(function() {
if (i > 1) {
$("#ke" + (i - 1)).html('');
i--;
}
});
});
As you can see from my script. There is only one Row <tr></tr>. I can alert it if it only one row. But when click Tambah Baris Baru there is another row showing up. I can't alert it. Here is my other javascript
$(".nipnya").change(function(){
$('.nipnya').each(function(i, obj) {
alert($('.nipnya').val());
});
});
So, can you tell me how to alert after onchange in every field that showing up dynamically.
Here is my fiddle https://jsfiddle.net/spc5884w/
Sorry for my bad english.
Currently what you are using is called a "direct" binding which will only attach to element that exist on the page at the time your code makes the event binding call.
You need to use Event Delegation using .on() delegated-events approach, when generating elements dynamically.
General Syntax
$(staticParentElement).on('event','selector',callback_function)
Example
$('table').on('click', ".nipnya", function(){
alert($(this).val());
});
DEMO

Alert button in innerhtml

I have a javascript function to call this result in a div innerhtml. How to alert 'Alert Function' when button on click?
$html.='<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th width="5%">#</th>
<th>Title</th>
<th>Action</th>
</tr>
</thead>
<tbody>';
$c=1;
foreach($titles AS $item){
$html.='<tr>
<td>'.$c.'</td>
<td>'.urldecode($item->title_content).'</td>
<td><button type="button" class="btn btn-danger" onclick="alert(\'**Alert Function**\')">Delete</button></td>
</tr>';
$c++;
}
$html.='</tbody>
</table>';
echo $html;
Thanks
Since this is PHP, you can directly insert onClick() event like this:
<td><button type="button" id="deleteButton" class="btn btn-danger" onclick="alertFunction()">Delete</button></td>
And then in JavaScript file:
function alertFunction()
{
alert('My custom text');
}
Let me know if that solves your problem and if I understood your question correctly.
If this onClick() is written in JavaScript itself, then remove that part and add additional line in JavaScript script:
document.getElementById("deleteButton").addEventListener("click", alertFunction);
Create a separate function to handle onclick event. This will be helpful in future if you want to pass any argument
<td><button type="button" class="btn btn-danger" onclick="clickButton()">Delete</button></td>
Somewhere in your code inside script tag create a function call clickButton()
function clickButton(){
alert('Alert Function')
}

Stop duplicate values when appending from array to table in real time

I am currently running through a loop to pull values our of an array, and most of it works, but when I add a 2nd value it duplicates the new value and previous value into the table.
So when I add a row with value 488 it works fine:
<tr class="exe">
<td class="sipname">1446033619.75</td>
<td class="siptd">SIP/488-00000027</td>
<td><button class="btn btn-default unmute" id="mute" type="submit">Unmute</button></td>
<td><button class="btn btn-default kick" id="kick" type="submit">Kick</button></td>
</tr>
When I add another value then say 487 then duplicates the same row 488, 488, 487 in that order as so:
<tbody id="sip">
<tr class="exe">
<td class="sipname">1446033619.75</td>
<td class="siptd">SIP/488-00000027</td>
<td><button class="btn btn-default unmute" id="mute" type="submit">Unmute</button></td>
<td><button class="btn btn-default kick" id="kick" type="submit">Kick</button></td>
</tr>
<tr class="exe">
<td class="sipname">1446033619.75</td>
<td class="siptd">SIP/488-00000027</td>
<td><button class="btn btn-default mute" id="mute" type="submit">Mute</button></td>
<td><button class="btn btn-default kick" id="kick" type="submit">Kick</button></td>
</tr>
<tr class="exe">
<td class="sipname">1446033747.78</td>
<td class="siptd">SIP/487-00000028</td>
<td><button class="btn btn-default mute" id="mute" type="submit">Mute</button></td>
<td><button class="btn btn-default kick" id="kick" type="submit">Kick</button></td>
</tr>
</tbody>
All I need is 488,487 in table rows without duplicates, when i refresh the page it works fine. I am using socket.io (Express), node.js and Jquery.
I did find a small workaround using jquery remove, but it affects functionality I have meaning a minor bug so I need to not use the jquery remove.
socket.on('sipname', function (data, datad) {
var sipname = '';
var sipid = '';
$('.exe').remove();
for (var i = 0; i < data.length; i++) {
sipname = data[i];
sipid = datad[i];
if (sipname) {
$sip.append('<tr class="exe">\
<td class="sipname">' + sipid + '</td>\
<td class="siptd">' + sipname + '</td>\
<td><button class="btn btn-default mute" id="mute" type="submit">Mute</button></td>\
<td><button class="btn btn-default kick" id="kick" type="submit">Kick</button></td>\
</tr>');
}
}
});
Any ideas or guidance would be appreciated, this is stopping me from completing my first version of my application.
1st : again and again ID must be unique
2nd: you can try this code .. I changed Ids to Class so be sure to change it in your css stylesheet .. and use data-sipname in siptd class
socket.on('sipname', function (data, datad) {
var sipname = '';
var sipid = '';
$('.exe').remove();
for (var i = 0; i < data.length; i++) {
sipname = data[i];
sipid = datad[i];
if (sipname) {
if($('#sip > tr > .siptd[data-sipname = "'+sipname+'"]').length < 1){
$sip.append('<tr class="exe">\
<td class="sipname">' + sipid + '</td>\
<td class="siptd" data-sipname="'+ sipname +'">' + sipname + '</td>\
<td><button class="btn btn-default mute" type="submit">Mute</button></td>\
<td><button class="btn btn-default kick" type="submit">Kick</button></td>\
</tr>');
}
}
}
});
hope it help
It looks like $sip is a "global"-ish value outside the socket.on function. It gets filled with values on the first .on() call, and then adds any values again on the second .on() call.
The way to fix could be one of:
Only send new data to any .on() function. That way when you append, you don't have any duplicates.
If data into the .on() function is complete each time, you can just empty the $sip array each call. $sip = [] and then append everything fresh each time.
The more complicated option is a check on each element of the array to see if it exists yet. If not, add it, otherwise skip it. Using a hash could make that easier as well, storing the ID as the key and that HTML string as the value. Then checking for existence is quick, !!$sip[ sipname ] (does the property sipname in the object $sip evaluate to true).

Categories

Resources