I'm trying to make dynamic table with javascript that elements can be dynamically added and removed with it.
Now, the remove function doesn't work probably.
I've tried .parent().parent().remove();
.parents("tr").remove();
.closest("tr").remove();
but they don't work.
The code to append to table :
$("table tbody").append("<tr><input type='hidden' name='label[]' value='" + $(".inputTitle").val() + "' /><input type='hidden' name='htmlText[]' value=\"" + html + "\" /><td>" + html + "</td><td>" + $(".inputTitle").val() + "</td><td>" + typeName + " ( " + crArabic + " )</td><td><a class='btn btn-danger deleteRow'><i class='fa fa-fw fa-times' aria-hidden='true'></i></a></td></tr>");
The Removal Code :
$("table tbody tr").on("click", ".deleteRow", function () {
$(this).parent().parent().remove();
});
The expected results to this is to add and remove table rows dynamically. However, the removing event isn't working.
You may have to read this SO answer Difference between $(document).on(“click”, “selector”, function …); and $(“selector”).on(“click”, function …) and change your code to:
$(document).on("click", ".deleteRow", function () { $(this).parent().parent().remove(); });
Related
I've created a table using an AJAX request to the database of items in our inventory displaying a picture/part name/price/stock remaining. When the table displays I would like to be able to click on any part of one of the rows and have it link to the item page associated with that item but it won't work.
I've tried the on.click with a static table written right into the html and it worked fine. Also if I direct the on.click script to just the table id instead of the table id and tr i can make the entire table clickable to the first row's href. So it appears that since the tr doesn't really exist in the html the javascript won't find it. Is there a way to get the script to recognize each 's href attribute?
HTML CODE + on.click script:
<html>
<body>
<table id="ctable">
<tbody id="tbody1" class="tbody1">
</tbody>
</table>
<script>
$('#ctable tr').click(function() {
var href = $(this).find("a").attr("href");
if(href) {
window.location = href;
}
});
</script>
</body>
</html>
.JS File CODE that creates table from .php file/mysql database
document.addEventListener('DOMContentLoaded', function() {
$.post('test.php', function(data) {
$("#tbody1").empty();
$.each(JSON.parse(data), function (index, value){
var eachrow = "<tr>" +
"<td class=\"image\">" + '<img src="images/thumbs/' +
value.image + '">' + "</td>" +
"<td>" + '<a href="' + value.link + '">' + value.part + "
</td>" +
"<td>" + value.price + "</td>"
"<td>" + value.stock + "</td>"
"</tr>";
$('#tbody1').append(eachrow);
});
});
}, false);
If you are dynamically adding rows, you need to either restructure your click event to listen from the context of the parent as in:
$("#tbody1").on("click", "tr", function(e) {
});
Assuming #tbody1 is a good place to start since you probably don't want the header row to be clickable. Or, every time you dynamically add rows, since the code is rebuilding the table, you can reattach the click event handlers:
$("#tbody1").empty();
$.each(JSON.parse(data), function (index, value){
var eachrow = "..
$('#tbody1').append(eachrow);
});
// or .on("click", function() { })
$("#tbody1 tr").click(function() { });
If you attach click handler via on, it would be good to then do an off as in:
$("#tbody1").off("click", "tr");
To remove the existing click handlers.
Hello and thank you for your time.
I have one doubt because I am trying to associate the ID I am reading from the Firebase database to the ID which identifies the button. It is important because of this button leads us to the event's modify page so then the event's ID is the one we use to load its data.
However those buttons' IDs look like they are one position forward let's see:
As you can see button 0 has ID Ejemplo nuevo which is the following row's event and so on.
Events:
Code:
Function's code:
function insertPlans() {
setReferences();
$("#title").html("Planes");
resetAllData();
$("#table thead").html("<tr>" +
"<td>ID</td> <td>Capacidad</td> <td>Fecha</td> <td>Descripción</td> <td>Ubicación</td> " +
"<td>Título</td> <td>Organizador</td> <td>Precio</td> <td>Prioridad</td><td>Asistentes</td>" +
"<td>Visibilidad</td></tr>");
dbRef.child('plans').once('value', function (snap) {
snap.forEach(function (planID) {
dbRef.child('plans/' + planID.key.toString()).once('value', function (snap) {
var row = "<tr><td><button id='new-button' class='btn btn-primary' onclick='saveEventName(this.id)'>Modificar evento</button>" + planID.key.toString() + "</td>";
$("#new-button").attr('id', planID.key.toString());
snap.forEach(function (fields) {
row += "<td>" + fields.val() + "</td>";
});
$("#table").find("tbody").append(row + "</tr>");
});
$("#table").find("tbody").append("</tr>");
});
});
}
Also if I do a console log as:
It prints the correct IDs:
Could you help me please?
$(‘#new-button’) is always referencing the previous row because we haven’t attached the row to the document yet.
You can first insert row then you can use the selector to change its id
Thank you for your help digitil. As you said I was editing the previous row because of the current one was not been added to the document.
The solution:
function insertPlans() {
setReferences();
$("#title").html("Planes");
resetAllData();
$("#table thead").html("<tr>" +
"<td>ID</td> <td>Capacidad</td> <td>Fecha</td> <td>Descripción</td> <td>Ubicación</td> " +
"<td>Título</td> <td>Organizador</td> <td>Precio</td> <td>Prioridad</td><td>Asistentes</td>" +
"<td>Visibilidad</td></tr>");
dbRef.child('plans').once('value', function (snap) {
snap.forEach(function (planID) {
dbRef.child('plans/' + planID.key.toString()).once('value', function (snap) {
var row = "<tr><td><button id='new-button' class='btn btn-primary' onclick='saveEventName(this.id)'>Modificar evento</button>" + planID.key.toString() + "</td>";
snap.forEach(function (fields) {
row += "<td>" + fields.val() + "</td>";
});
$("#table").find("tbody").append(row + "</tr>");
$("#new-button").attr('id', planID.key.toString());
});
$("#table").find("tbody").append("</tr>");
});
});
}
I use popover of the bootstrap and then the problem. when I write javascript for append data add to the table .
The data it can not be called a popover ,
but the first Table written, it can be called popover .
This a function code add table.
function myFunction() {
var addTable = "<tr>" +
"<td><a style='cursor:pointer' data-toggle='popover' title='Vat Detail' data-html='true' " +
"data-content='Vat <input type=\"text\" id=\"txtVat[]\" name=\"txtVat[]\" size=\"8\"> </br> " +
"Invoice <input type=\"text\" id=\"txtVatInvoice[]\" name=\"txtVatInvoice[]\" size=\"8\"> </br> " +
"DATE <input type=\"text\" id=\"txtVatDate[]\" name=\"txtVatDate[]\" size=\"8\"></br> '>" +
"VAT </a> </td>" +
"</tr>";
$("#myTable tbody").append(addTable);
};
Try to trigger the popover using Javascript, look here.
This could get the job done:
$(function () {
$('[data-toggle="popover"]').popover()
});
My end goal here is to take a button with a unique id from the index. Based off of the id is clicked (i.e. Which button I click) it deletes that corresponding table row. For example if I hit a delete button with an id of 1..then I want to delete the 1st table row within that table. I am having trouble understanding how I would do this.
Here is my code.
count = ["<TR>", "<TR>", "<TR>", "<TR>"]
$.each(count, function(index,value) {
index++;
$("#deletingRows table").append("<tr><td class='deleteRow' style='font-weight: bold;'>" + 'Row Number: ' + "<input type='text' name='rowNumber' id='rowNumber' style='margin-left: 45px;' value=" + index + ">" + "</input>" + "<input type='button' id='" + index + ' + "name='delete' value='Delete This Row'></input>" + "</td></tr>");
});
You can simplify this to :-
Give class delete to your button.
$('.delete').click(function(){
$(this).closest('tr').remove(); // closest('tr') will get you its parent tr and call .remove() to remove it.
});
or just use the name itself.
$('input[name=delete]').click(function(){
$(this).closest('tr').remove(); // closest('tr') will get you its parent tr and call .remove() to remove it.
});
See .closest()
Remember to put the click handler under document.ready.
I'm working my way through a JQuery Solution and for the most part it works but I"m stumped on seemingly a small detail I know I'm overlooking. Heck, maybe my implementation/approach needs to be reconsidered.
Here's the flow of what works.
1. Click an anchor that adds to a table.
2. Add CSS Class.
3. Disable (Unbind) click on after preappend().
4. From the table of dynamically added record remove table based on ID.
5. delete class that was added in step 2.
6. Bind 'click'
However, although I can bind the click and alert on it. The expected functionality does not allow me to step through the above process again.
The code in question:
HTML SAMPLE:
link that starts the process:
table that holds new records after click of link
<table id="carrier-table"><tbody></tbody></table>
JQUERY and Custom Javascript Function
<script type="text/javascript" id="removeCarrier">
function removeCarrierFromList(obj) {
var i = obj.parentNode.parentNode.rowIndex;
document.getElementById('carrier-table').deleteRow(i);
$('a#' + obj.id).removeClass('delete-carrier-company');
//alert(obj.id); //.hasClass('add-carrier-company').tostring() ); //
$('a#' + obj.id).bind('click', function() {
//alert('User clicked on ' + obj.id);
});
}
</script>
<script type="text/javascript" id="carrierListJS">
$(function() {
// Link
// This adds a carrier to a list
$('.add-carrier-company').click(
function() {
var target = $(this).attr("id");
alert(target);
$("#carrier-table").prepend("<tr id='carrierRow_" + target + "'>" +
"<td><a href='#' id='" + target + "' class='delete' onclick='removeCarrierFromList(this)'> </a></td>" +
"<td class='carrier-list-text'>" + target + " " + $("#name_" + target).val() + "</td>" +
"</tr>");
return false;
});
$('.add-carrier-company').click(
function() { $(this).addClass('delete-carrier-company').unbind('click'); }
);
});
</script>
There were a few issues I noticed with the code. For one thing, as #RussellUresti mentioned, you create two tags with the same ID. For another thing, if you're using ID's in a selector in jQuery, don't include the tag name, just use the id (ie. use $('#id') not $('a#id')) it will be faster (it won't break your code though).
I have created a jsfiddle to answer your question (though I rewrote most of it). :) I think it's what you're looking for.
Here's the code:
Test HTML
aa
bb
cc
10002
10003
<table id="carrier-table" style="border:1px solid #000"><tbody></tbody></table>
JavaScript
function addCarrier() {
var target = $(this).attr("id");
$("#carrier-table").prepend("<tr id='carrierRow_" + target + "'>" + "<td><a href='#' id='a" + target + "' class='delete'> </a></td>" + "<td class='carrier-list-text'>" + target + " " + $("#name_" + target).val() + "</td>" + "</tr>");
$('#a' + target).click(removeCarrierFromList);
$(this).addClass('delete-carrier-company').unbind('click');
return false;
}
function removeCarrierFromList() {
var $this = $(this);
var id = $this.attr('id').replace("a","");
$this.closest('tr').remove();
$('#' + id).removeClass('delete-carrier-company').click(addCarrier);
}
$(function() {
// Link
// This adds a carrier to a list
$('.add-carrier-company').click(addCarrier);
});