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

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>

Related

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

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");
});

How to add <tr> with delete button in javascript

I have implemented JavaScript functions for add <tr> with a delete button and edit button by clicking a button. Newly added delete button is not working properly. Edit button is working fine.
When i add a new <tr> manually working correctly. please help me to solve this. I have mentioned my code below.
newFile.html
<table class="table table-striped" id="maintable">
<thead>
<tr>
<th>Game Code#</th>
<th>Description</th>
<th>Subtotal</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>CHT01</td>
<td>2. Haricane Women</td>
<td>LKR. 500.00</td>
<td style="float: right">
<button type="button" class="btn btn-secondary btn-sm waves-effect waves-light" data-toggle="modal" data-target="#formemodal"><i class="fa fa-edit"></i> Edit</button>
<button type="button" class="btn btn btn-sm waves-effect waves-light delete"><i class="fa fa-bitbucket" ></i> Delete</button>
</td>
</tr>
</tbody>
</table>
<script>
$("#addnewrecord").click(function () {
$("#maintable").each(function () {
var tds = '<tr>';
//*jQuery.each($('tr:last td', this), function () {*
tds += '<td>' + $('#inputGroupSelect01code option:selected').text(); + '</td>';
tds += '<td>' + $('#inputGroupSelect01dscr option:selected').text(); + '</td>';
tds += '<td> LKR.' + $('#bidprice').val(); + '</td>';
tds += '<td style="float: right"> <button type="button" class="btn btn-secondary btn-sm waves-effect waves-light" data-toggle="modal" data-target="#formemodal"><i class="fa fa-edit"></i> Edit</button> <button type="button" class="btn btn btn-sm waves-effect waves-light delete"><i class="fa fa-bitbucket" ></i> Delete</button> </td>';
/*});*/
tds += '</tr>';
if ($('tbody', this).length > 0) {
$('tbody', this).append(tds);
} else {
$(this).append(tds);
}
});
});
</script>
newfile.js
$(document).ready(function(){
function SomeDeleteRowFunction(table,child) {
table.find(child).remove();
// you can also play with table and child (child is tr)
}
$(".delete").click(function(){
swal({
title: "Are you sure?",
text: "Once deleted, you will not be able to recover this imaginary file!",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
var $tbl = $(this).closest('table');
var $tr = $(this).closest('tr');
SomeDeleteRowFunction($tbl,$tr);
swal("Poof! Your imaginary file has been deleted!", {
icon: "success",
});
} else {
swal("Your imaginary file is safe!");
}
});
});
});
});
You need to reload the onclick action after you created your element. You can add to your js
function loadClick () {
$(".delete").click(function(){
swal({
title: "Are you sure?",
text: "Once deleted, you will not be able to recover this imaginary file!",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
var $tbl = $(this).closest('table');
var $tr = $(this).closest('tr');
SomeDeleteRowFunction($tbl,$tr);
swal("Poof! Your imaginary file has been deleted!", {
icon: "success",
});
} else {
swal("Your imaginary file is safe!");
}
});
});
}
and in your html :
if ($('tbody', this).length > 0) {
$('tbody', this).append(
}
else {
$(this).append(
}
loadClick();
note quite how I would have tackled it, but this is a bit tidier and still aimed at your html - I'm unclear on what swal is, a promise - when it return what is the value of this ?
swal can be subbed back in where I have confirm - but I recommend using window.confirm to get it working.
$(document).ready( function() {
let dFunc = function() {
console.log( this); // this is a tr to be sure
let tr = $(this);
if ( window.confirm( 'are you sure ?')) { // or whatever swal is
tr.remove();
}
}
$(".delete").on('click', function(e){ // jquery style
dFunc.call( $(this).closest('tr')); // "call" dFunc on the tr
});
// above has taken care of what is on the page
$("#addnewrecord").click(function () {
$("#maintable").each( function () { // each - ? ok ? multiple ?
var btn = $('<button type="button" class="btn btn btn-sm waves-effect waves-light delete"><i class="fa fa-bitbucket" ></i> Delete</button>');
btn.on('click', function(e){ // jquery style
dFunc.call( $(this).closest('tr')); // "call" dFunc on the tr
});
var tds = $('<tr />');
//*jQuery.each($('tr:last td', this), function () {*
tds.append( '<td />').html( $('#inputGroupSelect01code option:selected').text());
tds.append( '<td />').html( $('#inputGroupSelect01dscr option:selected').text());
tds.append( '<td />').html( 'LKR.' + $('#bidprice').val());
var cell = $('<td style="float: right"><button type="button" class="btn btn-secondary btn-sm waves-effect waves-light" data-toggle="modal" data-target="#formemodal"><i class="fa fa-edit"></i> Edit</button></td>');
cell.append( btn); // btn already has click active and defined
/*});*/
if ($('tbody', this).length > 0) {
$('tbody', this).append(tds);
} else {
$(this).append(tds);
}
});
});
});

How to pass the value to the bootbox in the loop

I have a problem. How to pass the value of the variable to the bootbox in the loop.
I have an array taken from the database and displayed in a loop:
<tr>
<td>Order nr1</td>
<td></td>
<td>
<button id="confirm-delete-modal" type="button" class="btn btn-danger btn-sm">Delete</button>
</td>
</tr>
<tr>
<td>Order nr2</td>
<td></td>
<td>
<button id="confirm-delete-modal" type="button" class="btn btn-danger btn-sm">Delete</button>
</td>
</tr>
And Js Bootbox:
$('#confirm-delete-modal').click(function() {
var tesst = "aaa";
bootbox.confirm({
message: "Delete?",
buttons: {
confirm: {
label: 'YES',
className: 'btn-danger'
},
cancel: {
label: 'NO',
className: 'btn-success'
}
},
callback: function (result) {
if(result)
{
window.location.href = "/"+ tesst
}
}
});
});
I would like to pass a separate Id to the link for each row in the loop.How can I do this?
I added a data-index="" to the HTML, this way you can send "parameters" to your click function.
$('.btn').click(function() {
var index = $(this).data("index");
alert(index);
});
<button id="confirm-delete-modal" type="button"
class="btn btn-danger btn-sm" data-index="1">Delete</button>
<button id="confirm-delete-modal" type="button"
class="btn btn-danger btn-sm" data-index="2">Delete</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Notice that I also changed your selector, since it was selecting just one HTML element id (you have two elements with the same id). Try to create a new class and selecting this class instead (in this example I used just the normal btn class).

for loop doesn't work - what do I do wrong?

I am new to JavaScript. I would appreciate if you could help me with the code: thanks!
I'm trying to hide the answers to 10 questions and show them when clicked on the right button!
It only shows the last answer when i klick any button!
var ya = document.getElementsByClassName("A");
$(ya).hide();
for (var i = 0; i < 10; i++){
var x = document.getElementsByClassName("idcheck");
var z = x[i].id;
console.log(x[i]);
$(x[i]).click(function() {
var y = document.getElementsByClassName(z);
$(y).show();
});
}
This is the html:
<p>
<button id="B<?php echo $drow['id'];?>" class="btn btn-primary idcheck" type="button" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
Lösung der Aufgabe!
</button>
</p>
<td><b class="text-success A B<?php echo $drow['id'];?>"><?php echo $brow['answertext'];?></b></td>
</tr>
<?php
}
?>
Your code is way more complicated than it needs to be. If you use jQuery, just stick with jQuery.
$(".A").hide();
$(".idcheck").on("click", function() {
var id = this.id;
$("." + id).show();
});
In your code you've use jQuery as well as bootstrap specific elements. So I'm assuming that you'r page has jQuery.
Please have a look at the following snippet
NOTE: I've cleaned up your HTML structure and removed unnecessary bootstrap specific classes
$('.idcheck') // We select all elements with the given class
.on('click', function() { // We attach a function for the 'click' event
var currID = $(this).attr('id').replace(/^B/i, ''); // We get teh ID fo the clicked buttona and remove 'B' from the start of it to it it's index
$('.B' + currID).show(); // We then use the index and generate a class selector to target the <td> tag to show it
})
.A {
display: none; // Hide the element initially
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<button id="B1" class="btn btn-primary idcheck" type="button">
Button for ID 1
</button>
</td>
<td><b class="text-success A B1">Content for ID 1</b></td>
</tr>
<tr>
<td>
<button id="B2" class="btn btn-primary idcheck" type="button">
Button for ID 2
</button>
</td>
<td><b class="text-success A B2">Content for ID 2</b></td>
</tr>
</table>
1) If you use jquery, use jquery!
2) have a look at scoping in js
$(".A").hide();
$(".idcheck").each(function(){
$(this).click(function() {
$("."+$(this).id).show();
});
});

Editable multiple forms on a table

I am using editable plugin to preform in place edit
This is the code I am using that I got from their Doc page, it is supposed to be used for adding new records, But I want to use it to modify records)
<script>
$(document).ready(function() {
//init editables
$('.myeditable').editable({
url: '/post',
placement: 'right'
});
//make username required
$('#new_username').editable();
//automatically show next editable
$('.myeditable').on('save.newuser', function(){
var that = this;
setTimeout(function() {
$(that).closest('td').next().find('.myeditable').editable('show');
}, 500);
});
//create new user
$('#save-btn').click(function() {
$('.myeditable').editable('submit', {
url: '/newuser',
ajaxOptions: {
dataType: 'json' //assuming json response
},
success: function(data, config) {
if(data && data.id) { //record created, response like {"id": 2}
//set pk
$(this).editable('option', 'pk', data.id);
//remove unsaved class
$(this).removeClass('editable-unsaved');
//show messages
var msg = 'New user created! Now editables submit individually.';
$('#msg').addClass('alert-success').removeClass('alert-error').html(msg).show();
$('#save-btn').hide();
$(this).off('save.newuser');
} else if(data && data.errors){
//server-side validation error, response like {"errors": {"username": "username already exist"} }
config.error.call(this, data.errors);
}
},
error: function(errors) {
var msg = '';
if(errors && errors.responseText) { //ajax error, errors = xhr object
msg = errors.responseText;
} else { //validation error (client-side or server-side)
$.each(errors, function(k, v) { msg += k+": "+v+"<br>"; });
}
$('#msg').removeClass('alert-success').addClass('alert-error').html(msg).show();
}
});
});
//reset
$('#reset-btn').click(function() {
$('.myeditable').editable('setValue', null)
.editable('option', 'pk', null)
.removeClass('editable-unsaved');
$('#save-btn').show();
$('#msg').hide();
});
});
</script>
And this is the html
<tr>
<td>adel</td>
<td></td>
<td></td>
<td></td>
<td><img src=""></img></td>
<td width="10%"><button id="save-btn" class="btn btn-primary btn-sm">Ok</button><button id="reset-btn" class="btn btn-sm pull-right">Reset</button></td>
</tr>
<tr>
<td>sdqsd</td>
<td></td>
<td></td>
<td></td>
<td><img src=""></img></td>
<td width="10%"><button id="save-btn" class="btn btn-primary btn-sm">Ok</button><button id="reset-btn" class="btn btn-sm pull-right">Reset</button></td>
</tr>
<tr>
<td>dzadz</td>
<td>from me with love</td>
<td>anywhere</td>
<td>http://justawebsite.com</td>
<td><img src=""></img></td>
<td width="10%"><button id="save-btn" class="btn btn-primary btn-sm">Ok</button><button id="reset-btn" class="btn btn-sm pull-right">Reset</button></td>
</tr>
Now everything works fine, Except if I edit one of the 2 first rows and hit Ok It will send the details of the last form http://justawebsite.com and sometimes it doesn't send anything, It is really messed up and I spent hours reading te documentation but I couldn't figure out the problem
As I said in my comment, you've got different elements with the same id, so the selectors won't work (id must be unique). Put them as class instead:
<tr>
<td>
adel
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
<a href="#" class="myeditable picture" data-type="text" data-name="picture" data-original-title="Enter Picture">
<img src="" />
</a>
</td>
<td width="10%">
<button class="btn btn-primary btn-sm save-btn">Ok</button>
<button class="btn btn-sm pull-right reset-btn">Reset</button>
</td>
</tr>
Here's a fiddle to get you started https://jsfiddle.net/virginieLGB/k2of9xor/1/
On there, you'll see that I've selected the editable elements you want to submit.
$('.save-btn').click(function() {
var that = $(this);
var allEditables = that.parents("tr").find(".myeditable"); // all ".myeditable" elements in the same "tr" as the ".save-btn" that was clicked on
allEditables.each(function() {
// here I've kept your code because I don't know what happens in your file, but maybe you need a bulk action
$(this).editable('submit', {
...
I don't know how your PHP file works, so don't know how you save your user and if you need to submit all fields at once or not. If so, you'll have to modify my answer a bit.
Have you tried refreshing it afterwards?
For me i noticed, that as soon as it was refreshed i got the result that i have been expecting, but only for one of them. However, i couldn't solve the problem yet.
Please let me know what kind of result you get.
Otherwise try debugging...disable one of the first rows and try it again..

Categories

Resources