How to add image in table cell - javascript

Hi I want to add image in table cell according to condition in table. I am using dynamic table as follow:
$.get('http://myDomain.com/RIA/topIndiaDetails.asp', function(data)
{
console.log("####"+data);
var up = new Image();
var down = new Image();
up.src = "../../jquery.mobile/images/up.png";
down.src = "../../jquery.mobile/images/down.png"
substr = data.split('$');
//alert(substr.length);
//var theader = '<table border="1">\n';
//<table id="auditOverview" border="1">
var theader = '<table border="1" id=\"tableId\">\n';
var tbody = '';
for (var out = 1;out<substr.length-1;out++)
{
//alert(substr[out]);
tbody += '<tr>';
var pra = substr[out].split('|^');
//alert('pra.length is: '+pra.length);
for (var i=0;i<pra.length-1;i++)
{
tbody += '<td>';
if (pra[i]=="Red")
{
pra[i].append("<img id='theImg' src='../../jquery.mobile/images/down.png'/>");
}
else if (pra[i]=="Green")
{
pra[i].append("<img id='theImg' src='../../jquery.mobile/images/up.png'/>");
}
tbody += pra[i];
tbody += '</td>'
}
tbody += '</tr>\n';
}
var tfooter = '</table>';
document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
});
Now I am checking condition as if (pra[i]=="Green") then I want to add image in cell insted of "Green" string and same for Red string. Any help will be appreciated. Thanks in advance.

instead of :
pra[i].append("<img id='theImg' src='../../jquery.mobile/images/up.png'/>");
do
pra[i] = "<img id='theImg' src='../../jquery.mobile/images/up.png'/>";

Related

Why Chrome adds tbody tag to each table row? [duplicate]

This question already has answers here:
Why do browsers insert tbody element into table elements?
(2 answers)
Why do browsers still inject <tbody> in HTML5?
(6 answers)
Closed 6 years ago.
I have two tables that fill up throw an event.
The stylesheet is made for that the even rows get painted white.
table {
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
But due Chrome adds tbody tag to each tr tag it's doesn't work.
The first table fill up throw back-end:
var prueba = {};
prueba = nuevaCadena[nuevaCadena.length - 1].replace(/<br>/g, "").split(",");
prueba.venta = prueba[0];
prueba.fecha = prueba[1];
prueba.heladeria = prueba[2];
//prueba.base.split(",");
//if (myElem === null) {
var contenido = document.getElementById("contenido");
var tr2 = document.createElement("TR");
if (contenido.getElementsByTagName("TH").length === 0)
{
contenido.appendChild(tr2);
tr2.innerHTML += "<th>Heladeria</th>";
tr2.innerHTML += "<th>Fecha</th>";
tr2.innerHTML += "<th>ID</th>";
} else {
var template = "<tr><td>{{heladeria}}</td><td>{{fecha}}</td><td>{{venta}}</td></tr>";
document.querySelector('#contenido').innerHTML += Mustache.render(template, prueba);
}
And the second works perfectly. It's fill up throw the select tag values.
var contenido = document.getElementById("contenido2");
var tr2 = document.createElement("TR");
var tr = document.createElement("TR");
if (contenido.getElementsByTagName("TH").length === 0)
{
contenido.appendChild(tr2);
tr2.innerHTML += "<th>Heladeria</th>";
tr2.innerHTML += "<th>Fecha</th>";
tr2.innerHTML += "<th>Sabor</th>";
tr2.innerHTML += "<th>Cantidad</th>";
}
contenido.appendChild(tr);
//var th = document.createElement("TD");
var option = ["heladerias", "sabores"];
var valor = document.getElementById("sabor_calorias");
var fecha = document.getElementById("fecha");
for (var i = 0; i <= 0; i++) {
var input = document.getElementById(option[i]).selectedIndex;
var input2 = document.getElementById(option[i]).options;
tr.innerHTML += "<td>" + input2[input].text + "</td>";
tr.innerHTML += "<td>" + fecha.value + "</td>";
for (var j = 1; j <= 1; j++) {
input = document.getElementById(option[j]).selectedIndex;
input2 = document.getElementById(option[j]).options;
tr.innerHTML += "<td>" + input2[input].text + "</td>";
tr.innerHTML += "<td>" + valor.value + "</td>";
tr.innerHTML += "<input type='button' class='borrar' value='x' onclick='deleted(this)'/>";
}
}
The results are this:
This question didn't work for me Why do browsers insert tbody element into table elements? i use Mustache.
When parsing the HTML syntax, the browser will insert a tbody tag, as explained in Why do browsers still inject <tbody> in HTML5?. By appending to the innerHTML each time, you're creating a new tbody each time. The HTML syntax can't represent a tr as a direct child of a table.
You could instead use
tr = table.insertRow()
tr.innerHTML='<td>foo<td>bar'
if you still wanted to write the row with innerHTML, or use td = tr.insertCell() as well.
The tags that chrome add are not needed, and shouldn't affect your code.
If you keep getting the error you might want to try going through to make sure you don't have any missed-placed characters.

My JavaScript/AJAX function only works while debugging

I am not very familiar with JavaScript and AJAX.
I am developing a webpage that displays information return by a ยง.getJSON / JQuery request. But this function only works, when I start debugging. I know that the debugger corrects the timing and scope from other post on this topic. But I cannot find my mistake. I do not realy need a long explaination, because as I said before I am not very familiar with JavaScript/AJAX. This is the script-part in the page (you can ignore the addDropDown() and the departmentSelected() functions(as far as i know)):
<script type="text/javascript">
var isSelected = [];
$(addDropDown);
function addDropDown(){
$.getJSON("./api/persence/departments/all", function(data, status){
if(status !== "success"){
alert(status);
}else{
var dropdownHead = "<button class='btn btn-primary dropdown-toggle' type='button' data-toggle='dropdown'>Abteilungen<span class='caret'><\/span><\/button>";
var dropdownBody = "<ul class='dropdown-menu'>";
var i;
for(i = 0; i < data.length; i++){
dropdownBody = dropdownBody + "<li><a href='javascript:departmentSelected(" + i + "," + data[i].departmentId + ");'>";
dropdownBody = dropdownBody + data[i].departmentName;
dropdownBody = dropdownBody + " - ";
dropdownBody = dropdownBody + data[i].departmentCity;
dropdownBody = dropdownBody + "<\/a><\/li>";
}
dropdownBody = dropdownBody + "<\/ul>";
dropdownHead = dropdownHead + dropdownBody;
$("#dropdown-list").append(dropdownHead);
isSelected.length = i + 1;
}
});
}
function departmentSelected(position, value){
if((isSelected[position] !== value)){
isSelected[position] = value;
}else{
isSelected[position] = "false";
}
loadTable();
}
function loadTable(){
var tHead = "<br><div class='table-responsive'><table class='table'><thead><tr><th>#</th><th>Name<\/th><th>Beruf<\/th><th>Anwesend<\/th><th>Arbeitsplatz<\/th><\/tr><\/thead>";
var tBody = "<tbody>";
for(var i = 0; i < isSelected.length; i++){
var counter = 0;
if(isSelected[i] !== "false"){
$.getJSON("./api/persence/departments/" + isSelected[i]).then(function(result, status){
if(status !== "success"){
alert(status);
}else{
for(var i = 0; i < result.length; i++) {
var employee = result[i];
tBody = tBody + "<tr> <td>" + counter + "<\/td>";
tBody = tBody + "<td>" + employee.academicTitle + " " + employee.lastName + " " + employee.firstName + "<\/td>";
tBody = tBody + "<td>" + employee.job + "<\/td>";
tBody = tBody + "<td>";
if(employee.persenceStatus === "Y"){
tBody = tBody + employee.persenceSince;
}else{
// if(employee.absenceReason !== null){
tBody = tBody + employee.absenceReason;
// }
//else{
// tBody = tBody + " ";
//}
}
tBody = tBody + "<\/td>";
tBody = tBody + "<td>" + employee.workplace + "<\/td>";
tBody = tBody + "<\/tr>";
counter++;
}
}
});
}
}
tBody = tBody + "<\/tbody> <\/table> <\/div>";
tHead = tHead + tBody;
document.getElementById("outputTable").innerHTML = tHead;
}
My Problem: I can not find what I have done wrong in this scriptpart, because the debugger (firebug) is able to optimize the code while debugging so it works perfectly fine. But if I am not in debug-mode, only the "head-line" of the table is displayed (the information is missing).
Thanks for your help.
This problem is about the finding element in DOM. Sometimes Js faster than DOM and Js can't find specific element in html DOM. You need to define js code in onLoad.
$(function() {
$(addDropDown);
});
OR
$(document).ready(function(){
$(addDropDown);
});
Inportant Info: If you include jQuery don't use JS specific functions. Sometimes it crash with jquery. Just use jQuery functions.
Example:
not good : document.getElementById("outputTable")
good : '$.("#outputTable")'
Ok, I solved the problem myself: I had to put the following part into the function called by the jQuery request (function(result, status).....)
tBody = tBody + "</tbody> </table> </div>";
tHead = tHead + tBody;
document.getElementById("outputTable").innerHTML = tHead;

JQuery append many many elements is made in one shot

I'm using jquery to append rows in a table.
I'm appending rows in an angular.forEach function in each loop but rows are rendered in my html page ine one shot : I mean the 1340 rows are displayed simultaneously insted of row by row.
I can not understand.
Here is an example of my code
angular.forEach(scope.contents, function(pack, indexPack) {
var bodyTag = '<tbody>';
if (pack.products.length > 0) {
angular.forEach(pack.products, function(product, indexProduct) {
bodyTag += '<tr>';
angular.forEach(scope.headers, function(header, indexHeader) {
var cellTag = '<td>';
var cellClass= '';
var cellContent = 'content 1';
cellTag += cellContent+'</td>';
bodyTag += cellTag;
});
bodyTag += '</tr>';
});
} else {
bodyTag += '<tr>';
angular.forEach(scope.headers, function(header, indexHeader) {
var cellTag = '<td>';
var cellClass= '';
var cellContent = 'content 2';
cellTag += cellContent+'</td>';
bodyTag += cellTag;
});
bodyTag += '</tr>';
}
bodyTag += '</tbody>';
$('#myTable').append(bodyTag);
});
Thanks for your help.

How can I insert a <tr> element into a dynamic table?

I hope someone has a clue for me. I am new to javascript and I am trying to build this structure with a dynamically generated table.
<table>
<tr>
<td>value1</td>
<td>value2</td>
<td>value3</td>
<td>value4</td>
</tr>
<tr>
<td>value5</td>
<td>value6</td>
<td>value7</td>
<td>value8</td>
</tr>
<tr>
<td>value9</td>
<td>value10</td>
<td>value11</td>
<td>value12</td>
</tr>
<tr>
<td>value13</td>
<td>value14</td>
<td>value15</td>
<td>value16</td>
</tr>
</table>
What I tried to do is to echo a <tr> after every 4th pair of <td>.
Like this:
var tbody_el = $("#somevalue_id"); //is the id of the table, which needs to be filled with `<tr>` and `<td>`.
var counter = 0;
$.each(TonsOfData.getValues(), function(index, somevalue) {
//var tr_el = $("<tr></tr>");
var td_checkbox_el = $("<td></td>");
var cbName = "cb_" + somevalue.displayName + "_name";
var cbId = "cb_" + somevalue.displayName + "_id";
var inputEl = $("<input type='checkbox' name='" + somevalue.displayName + "' id='" + cbId + "'/>");
inputEl.data("somevalueId", somevalue.id);
inputEl.attr("checked", "checked");
inputEl.change(valueChoicesClick);
var div_value_id = "div_value_" + somevalue.id + "_id";
var div_value_el = $("<div id='" + div_value_id + "' align='left'></div>");
var td_value = $("<td></td>");
td_checkbox_el.append(inputEl);
if(counter == 0 || (counter +1)%4 == 0){
echo "<tr>";
}
td_value.append(td_checkbox_el, "<br> Displayname: " + somevalue.displayName,"<br> Unit: "+ somevalue.unitstring," <br>",div_value_el);
if((counter +1)%4 == 0) {
echo "</tr>";
}
//tbody_el.append(tr_el);
}
);
Is this even possible?
Or am I going a totally wrong way?
Big thanks for any suggestions!!
EDIT:
I found a solution that worked for me. I doubt anyone will have the same issue, but I'd like to share it anyway.
I created a counter that gets incremented in the loop and gave the <td> parts a class-id.
if(counter<4){
td_value = $("<td class='select1'></td>");
}
if(counter>3 && counter <8){
td_value = $("<td class='select2'></td>");
}
if(counter>7 && counter <12){
td_value = $("<td class='select3'></td>");
}
if(counter>11 && counter <16){
td_value = $("<td class='select4'></td>");
}
if(counter>15 && counter <20){
td_value = $("<td class='select5'></td>");
}
After that I used the JQuery wrapAll()-function to add my <tr>. That did the trick.
$('#somevalue_id td.select1').wrapAll('<tr/>');
$('#somevalue_id td.select2').wrapAll('<tr/>');
$('#somevalue_id td.select3').wrapAll('<tr/>');
$('#somevalue_id td.select4').wrapAll('<tr/>');
$('#somevalue_id td.select5').wrapAll('<tr/>');
I know, it is not the most elegant solution but it works.
Thanks again to everyone that gave me hints, you helped me solve this!
You can use jquery and using .each for iterating and getting the fourth element in each iteration using .nth-child and inserting after using .insertAfter
Please find the example to mainuplate the table accordingly.
this is one way you can do it
<table class="test_table" id="test_table">
</table>
var tableEl = $(".test_table");
var noOfRows = 4;
var noOfColumns = 4;
//Empty the table in case there is anything already there
tableEl.each(function(){
var tableElObject = $(this);
for(i=0;i<noOfRows;i++)
{
rowStart = "<tr>";
for(j=0;j<noOfColumns;j++)
{
rowStart +="<td>"+"Test"+i+j+"</td>";
}
tableElObject.append(rowStart+"<tr/>");
}
});
http://jsfiddle.net/qg5hG/
if you want to create tables trs and tds dynamically this way can be better for you....
var table = document.createElement('table');
table.setAttribute('border','0');
table.setAttribute('cellspacing','5');
table.setAttribute('cellpadding','5');
table.setAttribute('width','100%');
var tr = table.insertRow(-1);// "-1"s meaning add tr to end of table if you want to add top of table you must use "0"
tr.id = 'Tr1 ID';
var td = tr.insertCell(-1);
td.innerHTML = 'Inside of TD 1';
var td = tr.insertCell(-1);
td.innerHTML = 'Inside of TD 2';
var tr = table.insertRow(-1);
var td = tr.insertCell(-1);
td.innerHTML = 'Inside of TD 1';
var td = tr.insertCell(-1);
td.innerHTML = 'Inside of TD 2';

How to read value of Textbox which is inside table

I need to read the value of textbox which is inside the table.
Following is how I create table.
var theader = '<table border = "1" id = "MarksTable">\n';
var tbody = '';
for ( var i = 0; i < total_rows; i++) {
tbody += '<tr>';
for ( var j = 0; j < total_col; j++) {
tbody += '<td name=' + "cell" + i + j + '>';
if (i > 0) {
tbody += '<input type="text" value = "marks" name="inputcell1'+j + '">';
} else {
tbody += '<b>' + subjectList[j] + '</b>';
}
tbody += '</td>';
}
tbody += '</tr>\n';
}
var tfooter = '</table>';
document.getElementById('wrapper').innerHTML = theader
+ tbody + tfooter ;
and below is my attempt to read text box value:
function readTableData(){
var marks = [];
var table = document.getElementById("MarksTable");
var column_count = table.rows[1].cells.length;
var row = table.rows[1];
if(column_count>0){
for(var index = 0; index < column_count;index++){
marks[index] = row.cells[index].innerHTML;
}
}
return marks;
}
Here, row.cells[index].innerHTML gives the output '<input type="text" value = "marks" name="inputcell10">.
Try this:
function readTableData(){
var marks = [];
var table = document.getElementById("MarksTable");
var column_count = table.rows[1].cells.length;
var row = table.rows[1];
if(column_count>0){
for(var index = 0; index < column_count;index++){
marks[index] = row.cells[index].getElementsByName('inputcell' + index)[0].value;
//Or marks[index] = document.getElementsByName('inputcell' + index)[0].value;
}
}
return marks;
}
<!DOCTYPE html>
<html>
<head>
<style>
table, td {
border: 1px solid black;
}
</style>
</head>
<body>
<p>Click the button to add a new row at the first position of the table and then add cells and content.</p>
<div id="tableContainer">
</div>
<br>
<button onclick="myFunction()">Try it</button>
<button onclick="readTableData()"> Read it </button>
<script>
function myFunction() {
var tab = '<table id="MarksTable">';
var counter = 0;
for(i = 0; i< 4; i++){
tab = tab + '<tr><td rowspan = "4"> Dept1 </td><td> <input type="text" id="inputcell'+counter+'" value="'+i+'"/> </td></tr>';
counter++;
tab = tab+'<tr><td> <input type="text" id="inputcell'+counter+'" value="'+i+'"/> </td></tr>';
counter++;
tab = tab+'<tr><td> <input type="text" id="inputcell'+counter+'" value="'+i+'"/> </td></tr>';
counter++;
tab = tab+'<tr><td> <input type="text" id="inputcell'+counter+'" value="'+i+'"/> </td></tr>';
counter++;
}
tab = tab + '</table>';
document.getElementById("tableContainer").innerHTML = tab;
}
function readTableData(){
var val;
var table = document.getElementById("MarksTable");
var column_count = table.rows[1].cells.length;
var rowcount = table.rows.length;
alert(rowcount);
if(column_count>0){
for(var index = 0; index < rowcount;index++){
var row = table.rows[index];
val = document.getElementById("inputcell"+index);
alert(val.value);
//marks = row.cells[0].getElementsByName('inputcell').value;
//Or marks[index] = document.getElementsByName('inputcell' + index)[0].value;
}
}
alert(val);
}
</script>
</body>
</html>

Categories

Resources