Using deleteRow to delete a row by id - javascript

Anyways, I'm currently doing a repeater-type of add/delete rows. Looking through the documentation, it only appears to manual delete based on row number.
Take not that this is called under a LaravelBlade foreach loop so I added respective IDs when being clicked
var approverCount = 0;
function add(id)
{
var table = document.getElementById("table" + id);
var row = table.insertRow();
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "Hi";
cell2.innerHTML = "Hello";
testCount++;
row.id = 'teste_' + id + '_' + testCount;
}
function remove(tableId, rowId)
{
var table = document.getElementById(tableId);
var row = document.getElementById(rowId);
table.deleteRow(row);
// stopped here due to constraints from problem
}

If your goal is to delete a table row by its id, then it can be done purely from that one id, and it's fairly straightforward with remove (slightly modern) or parentNode and removeChild (universally supported):
// On a modern browser
document.getElementById(theRowID).remove();
or
// On slightly less modern browsers
var row = document.getElementById(theRowID);
row.parentNode.removeChild(row);
If for some reason you really want to use the table's deleteRow, then you'd use the row's rowIndex:
table.deleteRow(row.rowIndex);

You must use row number instead of id attribute:
table.deleteRow(0);

Related

link a checkbox to an object in Javascript

Suppose I have a table which is populated by filling out a form on a page and clicking the submit button.
The last column of the table is a Completed section with a checkbox on each row. On clicking on the checkbox I want to change the .completed property from false to true on that object.
How can I distinguish which checkbox was clicked and change the property from that row?
this.addRowToTable = function() {
return "<tr id='tableRow'><td>" + this.app + "</td><td>" + this.priority + "</td><td>" + this.date + "</td><td>" + this.additionalNotes + "</td><td>" + "<input type='checkbox' class='checkApp[]' value='" + this.completed + "' />" + "</td></tr>";
};
I have all the checkboxes in the checkApp array, but Im not sure where to go from there?.
This is called when the form is submitted:
function addAppointment() {
if (txtApp.value == "" || txtPriority.value == "" || txtDate.value == "" || {
alert("Please fill all text fields");
} else {
var app = new Appointment(txtApp.value, txtPriority.value, txtDate.value, txtNotes.value, false);
apps.push(app);
localStorage.setItem("apps", JSON.stringify(apps));
clearUI();
}
updateTable();
updateTable() loops through all objects in my array and adds them between table tags:
for (var i = 0; i < apps.length; i++) {
var app = new Appointment(apps[i].app, apps[i].priority, expenses[i].date, apps[i].notes, false);
tblHTML += app.addRowToTable();
}
My Appointment Object:
function Appointment(app, priority, date, notes, completed) {
this.app = app;
this.priority = priority;
this.date = date;
this.additionalNotes = notes;
this.completed = completed;
this.addRowToTable = function { ... };
}
First of all, in HTML, id attributes should be unique. So, make sure table rows have unique IDs. At the moment, all of them have the identical ID of tableRow.
Besides, you should consider using a framework/library such as jQuery for real-world scenarios rather than creating the DOM elements, etc. manually.
Now back to the original problem: if you use the DOM API rather than string concatenation to create the table rows, you can add custom fields to the DOM objects representing the table rows. So, from each table row, you can have a reference back to its corresponding Appointment object:
var row = document.createElement("tr");
row.appointment = this;
Similarly, you can use the DOM API to create the table cells as well as the checkbox:
addTd(row, this.app);
addTd(row, this.priority);
addTd(row, this.date);
addTd(row, this.additionalNotes);
var input = document.createElement("input");
var td = document.createElement("td");
td.appendChild(input);
row.appendChild(td);
input.setAttribute("type", "checkbox");
input.setAttribute("class","checkApp[]"); // Why checkApp[]? checkApp or check-app make more sense
input.setAttribute("value", this.completed);
where addTd is the following function:
function addTd(row, innerHTML) {
var td = document.createElement("td");
td.innerHTML = innerHTML;
row.appendChild(td);
}
Now that you are using the DOM APIs, you can easily attach event listeners to each checkbox object as well.
Then inside the event listener you can get a reference back to the Appointment corresponding to the row you
have changed its checkbox:
var row = document.createElement("tr");
row.appointment = this;
addTd(row, this.app);
addTd(row, this.priority);
addTd(row, this.date);
addTd(row, this.additionalNotes);
var input = document.createElement("input");
var td = document.createElement("td");
td.appendChild(input);
row.appendChild(td);
input.setAttribute("type", "checkbox");
input.setAttribute("class","checkApp[]"); // Why checkApp[]? checkApp or check-app make more sense
input.setAttribute("value", this.completed);
input.addEventListener("change", function(event) {
var row = this.parentNode.parentNode,
appointment = row.appointment;
// change appointment however you like
});

Bind jquery datepicker to dynamic row Textfield

In HTML table, there is a text field on which I have binded Jquery datepicker control:
$("#CreatedOnValue").datepicker();
It works fine. The table is dynamic and user can add as many rows as he wants by clicking on add button adjacent to each row. I am trying to bind datepicker control to dynamic rows as well and it is not working. Here is function which is executed when user clicks on row add button:
function addGroupRow(e) {
var rowId = e.parentNode.parentNode.id;
var newindex = getConditionPlacementIndex(rowId);
var row = document.getElementById("advancedSearch").insertRow(newindex);
...
// create table cell of datetime textbox
var cell3 = row.insertCell(3);
cell3.id = row.id+"_cell3";
var strHtml3 = "<INPUT class=\"textbox\" TYPE=\"text\">";
cell3.innerHTML = strHtml3.replace(/!count!/g, count);
$("#" + cell3.id).datepicker();
}
Its not working and datepicker does not appear on dynamic text field. Any suggestion?
Thanks.
Use class instead of id(Give dynamically generated textboxes a class say 'textbox') and do as :
$('body').on('focus',".textbox", function(){
$(this).datepicker();
});​
Working Demo
I have resolved this issue by following code modification:
var cell3 = row.insertCell(3);
var cell3Id = row.id+"_cell3";
var strHtml3 = "<INPUT class=\"textbox\" TYPE=\"text\" id=" + cell3Id + ">";
cell3.innerHTML = strHtml3.replace(/!count!/g, count);
$("#" + cell3Id).datepicker();

jQuery: dialog() of table data from ajax not showing

$(function () {
$('.referral').on('click', function () {
$('#hold').html($(this).find('DIV').html());
$('#hold').dialog();
});
});
$(function getTableData() {
$.ajax({
url: 'interface_API.php',
data: "",
dataType: 'json',
success: function (data) {
setTimeout(function () {
getTableData()
}, 1000);
var body = document.getElementById('tbody');
body.innerHTML = '';
for (var i in data) {
var row = data[i];
var customerCode = row.CustomerCode;
var phone = row.PhoneNumber;
var thetime = row.TimeStamp;
var tr = document.createElement('TR');
tr.className += " " + "referral";
body.appendChild(tr);
var td = document.createElement('TD');
td.appendChild(document.createTextNode(customerCode));
tr.appendChild(td);
var td = document.createElement('TD');
td.appendChild(document.createTextNode(phone));
tr.appendChild(td);
var td = document.createElement('TD');
td.appendChild(document.createTextNode(thetime));
tr.appendChild(td);
var tr2 = document.createElement('TR');
body.appendChild(tr2);
var td2 = document.createElement('TD');
var divE = document.createElement('DIV');
divE.className += " " + "extra";
var text = document.createTextNode("sage, extra, etc");
divE.appendChild(text);
td2.appendChild(divE);
tr2.appendChild(td2);
}
}
});
});
I have data from a JSON api that is imported using ajax.
This is displayed to a table, of which the rows are created using JS.
With each row, there is an additional row of 'additional' data that is hidden from the user.
on click of a row, i wish for a dialog to appear displaying this 'additional' data.
Initally i tryed todo this with writing out the rows in "raw format" (var row = "<tr><td>...</td></tr>" etc) however i read that this does not work well with javascript functions like the one i am trying to execute as the DOM has already been set (i'm not 100% sure about that). This is why i use JS to create each element & do it correctly, to some respect.
However, i am still unable to get the dialog to appear
Notes.
below the table (html hard coded) is a empty div which is used as a holder for when a dialog is to appear.
I have had success before when the data is static & ajax is not involved
I found the solution.
It seems that the JS .on('click', function() was not being called, or registered at the right point. i checked on the DOM properties using chrome dev tools & .referral's onclick property was null.
Instead, i set the onclick attribute of each <TR> with the function clicks() like so:
var tr = document.createElement('TR');
tr.setAttribute("onclick", "clicks(this)");
With,
function clicks(param){
$('#hold').html($(param).find('DIV').html());
$('#hold').dialog();
};

HTML Table content insert and clear using javascript

I have a table and assigned a id to it. Initially there is no content.i.e., just the table tag.
I am using this to clear the table contents
function emptyTable ( tableRef )
{
var resultCount = tableRef.rows.length;
for ( var i=0; i<resultCount; i++)
{
if ( tableRef.rows[tableRef.rows.length-1].cells[0].tagName == "TD" )
{
tableRef.deleteRow(tableRef.rows.length-1);
}
}
}
tableRef will have the table id. For first time i have clear the table and the rows are inserted.
var resultListRef = document.getElementById("showReferencesDet");
var row = resultListRef.insertRow(0);
var newCell = row.insertCell(0);
newCell.innerHTML = 'Select';
var newCell2 = row.insertCell(1);
newCell2.innerHTML = 'Reference Number';
var row = resultListRef.insertRow(resultListRef.rows.length);
var newCell = row.insertCell(0);
name="referenceId" value="' + id + '" />';
newCell.innerHTML = '<input type="checkbox" id="referenceId" name="referenceId" value="' + allVars + '" />';
var newCell2 = row.insertCell(1);
newCell2.innerHTML = RefNo;
It works for the first time but didn't works in the 2nd time.
Please help to solve it.
just change your for loop
function emptyTable ( tableRef )
{
document.getElementById(tableRef).innerHTML='';
}
Instead of:
var row = resultListRef.insertRow(resultListRef.rows.length);
you can do:
var row = resultListRef.insertRow(-1);
and the row will be inserted as the last row.
Removing the rows of a table doesn't necessarily remove all content, it may still contain empty text nodes, thead and tfoot elements, etc. Consider:
function emptyTable ( tableRef ) {
while (tableRef.firstChild) {
tableRef.removeChild(tableRef.firstChild);
}
}
That will clear everything from inside the table (but not properties and attributes of the table itself) as if you had <table ... ></table>.
However, you may want to keep header rows and footers. In that case, you just want to remove the tBody elements:
function emptyTableBodies ( tableRef ) {
var tBodies = tableRef.tBodies;
for (var i=tBodies.length; i;) {
tableRef.removeChild(tBodies[--i]);
}
}
so you can do:
<table id="t0">
<thead>
<tr><th>head
</thead>
<tr><td>0
<tr><td>0
<tr><td>0
<tr><td>0
</table>
<button onclick="emptyTableBodies(document.getElementById('t0'))">Empty table bodies</button>
Note that a table with no content is not valid, so fix that as soon as you can after the above.

How to get HTML table row data, based on checkbox selection in each row?

I have a table dynamically created with java script.It has one checkbox in each row as the first column.I want to fetch the row data based on the checkboxes selected of respective rows.
var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell0 = row.insertCell(0);
var cell1 = row.insertCell(1);
cell0.innerHTML = 'Select';
cell1.innerHTML = 'Epic';
cell0.innerHTML = " checkbox html code ";
cell1.innerHTML = epicSeries[j];
Actually too many columns are there I am putting just two of them. I have lot of epics down the column header 'epic' and one checkbox as the first column in each row.I want row data based on checkbox selcted.
Sorry code was too long so I cant paste all of them.
Having now an example of your code and bit more clear requirement, i think you should do the folowing:
$('#myTable input[type=checkbox]:checked').each(function() {
var row = $(this).parent().parent();
var rowcells = row.find('td');
// rowcells contains all td's in the row
// you can do
// rowcells.each(function() {var tdhtml = $(this).html(); });
// to cycle all of them
});
If you have table like that:
<table>
<tr>
....
<td><input type="checkbox" name="cb1" checked></td>
...
</tr>
</table>
This code will return all <tr>'s with checked checkboxes
If row selecting check box is in a deeper level you should as more .parent()'s as needed
This exemple uses jQuery of course.
$('table#tableid input[type=checkbox]').each(function() {
if ($(this).is(':checked')) {
....
}
});
something like that i supose
This is what I used in my case using jquery:
$('.chkbox').click(function(){
var row = jQuery(this).closest('tr');//your nearest row for the check box
$(row).each(function(){
//get all data using the id and use/store it
$(this).find(".item").html();
});
});
For each checkbox and for each item in a row give a class(I used chkbox for all checkboxes and item, price etc. for all items of a single row)

Categories

Resources