$(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();
};
Related
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);
I´m filling a table with jquery from a JSON data source
var data = dataJSONMOV,
fragment = document.createDocumentFragment(),
tr, td, i, il, key;
for(i=0, il=data.length;i<il;i++) {
tr = document.createElement('tr');
for(key in data[i]) {
td = document.createElement('td');
td.appendChild( document.createTextNode( data[i][key] ) );
tr.appendChild( td );
}
//Button generation code should go here (see below)
fragment.appendChild( tr );
}
$('#mytable tbody').append( fragment.cloneNode(true) );
I want to add a button in the end of each row which calls a function displayInformation(string ID) with a parameter from the first coloumn of that row.
How can I accomplish that?
I tried it with this code but it doesn`t show me any buttons
//Button generation code
var btn = document.createElement('input');
btn.type = "button";
btn.className = "btn";
btn.value = data[i][0];
btn.onclick = (getTestAlert(data[i][0]));
tr.appendChild(btn);
You are on right direction on how add the button. You can add it and them add an event listener to the table:
$('#mytable').on("click", "input", function() {
});
// Or
$('#mytable').on("click", "input", getTestAlert);
So, to know what id it belongs, add a data attribute:
var btn = document.createElement('input');
btn.dataset.id = data.id;
And how to retrieve it:
$('#mytable').on("click", "button", function() {
var id = $(this).data("id"); // For jQuery
id = this.dataset.id; // For vanilla
});
Your loop would probably end like this:
for(i=0, il=data.length;i<il;i++) {
tr = document.createElement('tr');
for(key in data[i]) {
td = document.createElement('td');
td.appendChild( document.createTextNode( data[i][key] ) );
tr.appendChild( td );
}
// Add button in last column
var btn = document.createElement('input');
btn.type = "button";
btn.className = "btn";
btn.value = data[i][0];
btn.onclick = (getTestAlert(data[i][0]));
tr.appendChild(btn);
fragment.appendChild( tr );
}
Working demo
Besides, I don't know if its some kind of a requirement, but if you're using jQuery, you should use it for your entire code, like the elements creating as well. Creating elements may be odd in some browsers and jQuery takes care of it. If you're interested, your code should became something like:
var data = dataJSONMOV,
fragment = document.createDocumentFragment(),
key, html = "";
for(var i=0, il=data.length;i<il;i++) {
html+= "<tr>";
for(key in data[i]) {
html+= "<td>" + data[i][key] + "</td>";
}
html+= "<td><input type='button' class='btn' value='Click me' data-id='" + data[i].id + "' /></td></tr>";
}
$("#mytable").append(html);
Pretty short, huh ?
Because you're populating the table dynamically, you need to add a click listener based on some parent defined in the html. Assuming this is the case for '#myTable tbody' and that the parameter from the first column of that row that you need for displayInformation() is accessible via .text(), you could use
$(document).ready(function() {
$('#myTable tbody').on('click', 'input[type="button"]', function() {
displayInformation($('td:first-child', $(this).parents('tr')).text());
});
});
to create the click listener for the row's button.
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
});
I have created ten separate tables in javascript using HTML tags. I now want to put those tables in a grid format so I thought putting them into another table would work. This code just makes an empty table appear. Any help? Thanks!
document.getElementById('InstalledApps').innerHTML += '<table id="bigAppsTable" border="1"><td>';
for (var i = 9; i>-1;i--){
document.getElementById('InstalledApps').innerHTML += '<table id="appsTable'+i+'" border="1"><tr></tr>';
var thirdRow=document.getElementById("appsTable"+i).insertRow(1);
if (the_data[i]['release'] != null){
thirdRow.insertCell(-1).innerHTML="<b>Release: ";
thirdRow.insertCell(-1).innerHTML=the_data[i]['release'];
}
var secondRow=document.getElementById("appsTable"+i).insertRow(1);
secondRow.insertCell(-1).innerHTML="<b>Version: ";
secondRow.insertCell(-1).innerHTML=the_data[i]['version'];
var firstRow=document.getElementById("appsTable"+i).insertRow(1);
firstRow.insertCell(-1).innerHTML="<b>Name:";
firstRow.insertCell(-1).innerHTML=the_data[i]['name'];
}
Since you're dynamically creating tables, why not use the DOM API? (ie. not innerHTML)
Here is a good place to get your started: https://developer.mozilla.org/en-US/docs/Web/API/document.createElement
Try like this
var aTable = document.createElement('table');
for (var i = 0, tr, td; i < 9; i++) {
tr = document.createElement('tr');
td = document.createElement('td');
td.appendChild(document.createTextNode("some text"));
tr.appendChild(td);
aTable.appendChild(tr);
}
//update with id
document.getElementById('table').appendChild(aTable);
I've been having a hard time trying to append new headers to tables I build dynamically using data grabbed from an AJAX call.
I've already asked here a question about my problem, but it seems that there's no logical answer to it.
So my problem is that I can't actually get the table I want to append my new info to, what I tired was this:
console.log(id); //This prints the right id!
//THIS is not working...
$('#'+id+' tr:first').append("<td>Well "+(wellCounter)+"</td>");
//...
//$('#'+401+' tr:first').append("<td>Well "+(wellCounter)+"</td>");--this will work
table+="<td>M "+fourthLevel.male+"</td>";
table+="<td>H "+fourthLevel.herm+"</td>";
But it didn't work, so I was wondering if you can help me with another way to get the same functionality without using the id to get the table. Maybe the closest function will work but I don't have experience with that, and I tried it but failed.
Here the full code:
$.each(data, function(index, firstLevel) {
$.each(firstLevel, function(index2, secondLevel) {
var id = firstLevel['id'];
var author = firstLevel['author'];
var date = firstLevel['date'];
var experimental_conditions = firstLevel['experimental_conditions'];
if(index2 == 'items'){
var table = '<div class=tableWrapper><table id=\"'+id+'\" class=\"experimentTable\">';
table += '<input id=\"basketButton\" type=\"submit\" value=\"Add to basket\" class=\"basketButton\" experimentBatch=\"'+id+'\"> <div class="superHeader"><span class=\"superHeader\">Date: '+date+', By '+author+'</span><br /><span class=\"subHeader\">Experimental conditions: '+experimental_conditions+'</span>'
table += '<tr><td></td><td COLSPAN=2>Totals</td></tr>';
table += '<tr id="header"><td width="20%">Genotype</td><td width="10%"><img src="images/herma.png"></td><td width="10%"><img src="images/male.png"></td>';
//for each table
$.each(secondLevel, function(index3, thirdLevel) {
var nWells = 0;
table += "<tr><td>"+thirdLevel['mutant_name_c']+"</td><td>"+thirdLevel['herm_total']+"</td><td>"+thirdLevel['male_total']+"</td>";
currentRow = 3;
wellCounter = 0;
//for each row
$.each(thirdLevel, function(index4, fourthLevel) {
wellCounter++;
if (fourthLevel.date_r != undefined){
console.log(id);
//THIS is not working...
$('#'+id+' tr:first').append("<td>Well "+(wellCounter)+"</td>");
//...
table+="<td>M "+fourthLevel.male+"</td>";
table+="<td>H "+fourthLevel.herm+"</td>";
}
});
});
table +='</table></div>'
$('#searchResults').append(table);
}
});
});
NOTE: Male and herm are worm genders, not options!
I didn't go through your code, but when I'm working with dynamic table in jquery i try with Jquery "OBJECT". something like
var $tbl = $('<table />'), $tr=$('<tr />'), $td=$('<td />');
then you can add attr, append etc, and is much easier to read, and manipulate.
$tbl.attr('id',id).append($tr.append($td);
etc.