Dynamically created <th> get's lower position why? - javascript

Below is the code snippet where I've created <th> using jquery.
My question is, How can I place the dynamically created <th> above the two <td>'s which I've created below.
I've tried to search a lot but all the results where adding to the end only, not to the top of the <td>.
$(document).ready(
function() {
var noOfRow = document.getElementById("addItemTable").rows.length;
var temp = document.getElementById("addItemTable");
var table = temp.getElementsByTagName('tbody')[0];
var row = table.insertRow(-1);
var cell2 = row.insertCell(0);
var cell3 = row.insertCell(1);
cell2.innerHTML="this is inside table div";
cell2.style="border: dashed;"
cell3.innerHTML="this is inside another another div";
cell3.style="border: dashed;"
var thContent = '<th class="col2">' + '<br>' + 'test' + '&nbsp &nbsp' + '*' + '' + '</th>'
var mainTable = document.getElementById("addItemTable");
$('#addItemTable>tbody>tr').append(thContent);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="m-content" id="elementDiv">
<table id="addItemTable">
<tbody>
</tbody>
</table>
</div>

You must use prepend insead of append :)
$(document).ready(
function() {
var noOfRow = document.getElementById("addItemTable").rows.length;
var temp = document.getElementById("addItemTable");
var table = temp.getElementsByTagName('tbody')[0];
var row = table.insertRow(-1);
var cell2 = row.insertCell(0);
var cell3 = row.insertCell(1);
cell2.innerHTML="this is inside table div";
cell2.style="border: dashed;"
cell3.innerHTML="this is inside another another div";
cell3.style="border: dashed;"
var thContent = '<th class="col2">' + '<br>' + 'test' + '&nbsp &nbsp' + '*' + '' + '</th>'
var mainTable = document.getElementById("addItemTable");
$('#addItemTable>tbody>tr').prepend(thContent);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="m-content" id="elementDiv">
<table id="addItemTable">
<tbody>
</tbody>
</table>
</div>

Related

Why am I not getting the IDs from innerHTML?

I have HTML & javascript code where you can click a button to add a row to an existing table. I want to make sure that each row's dropdowns have the correct IDs in ascending order. The middle rows can get deleted, and I need to adjust the IDs.
function addRow(){
var table = document.getElementById('myTable');
//Get the number of rows in the table, and use (+1) value for the IDs later
var rowCount = table.tBodies[0].rows.length;
var tbodyRef = table.getElementsByTagName('tbody')[0];
// Insert a row at the end of table
var newRow = tbodyRef.insertRow();
// Insert a cell at the end of the row
var cell0 = newRow.insertCell(-1);
cell0.innerHTML = '<select id="firstDropdown' + (rowCount + 1) + '"></select>';
var cell1 = newRow.insertCell(-1);
cell1.innerHTML = '<select id="secondDropdown' + (rowCount + 1) + '"></select>';
var cell2 = newRow.insertCell(-1);
cell2.innerHTML = '<button onclick=deleteRow()>Delete</button>';
/*Here, I want to get the list of ID's of the firstDropdown of
each row (for debugging purposes). But this is not printing anything.
Why is this code below not printing the first dropdown's ids of each row? */
console.log("------------------------");
for(var i=0; i<table.tBodies[0].rows.length; i++){
console.log(table.tBodies[0].rows[i].cells[0].id);
}
}
function deleteRow(){
var td = event.target.parentNode;
var tr = td.parentNode;
tr.parentNode.removeChild(tr);
}
My HTML code is below:
<button onclick=addRow()>Add row</button>
<br>
<table id="myTable">
<thead>
<th>1st dropdown</th>
<th>2nd dropdown</th>
<th>Remove</th>
</thead>
<tbody>
<!--Rows will be added/deleted dynamically-->
</tbody>
</table>
I will need to update dropdowns' IDs later when rows are deleted.
I was hoping to do it the same way: table.tBodies[0].rows[i].cells[0].id = "firstDropdown" + (i+1); but I am not sure if this is even going to work now.

Transfer Table TD in textbox

This is the way on how I populate data in my table.
<script>
function GenerateTable() {
<? var data = getData(); ?>
var table = document.getElementById("TableContainer");
<? for (var i = 12; i < data.length; i++) { ?>
var getval;
var row = table.insertRow(-1);
var row_did = row.insertCell(0);
var row_area = row.insertCell(1);
var row_cusname = row.insertCell(2);
var row_pic = row.insertCell(3);
var row_remarks = row.insertCell(4);
var row_status = row.insertCell(5);
var row_docudate = row.insertCell(6);
var row_button = row.insertCell(7);
row_did.innerHTML = '<td id="dataid" class="dataid">'+ <?= data[i][0] ?> + '</td>';
row_area.innerHTML = '<td id="area" class="area">'+ <?= data[i][1] ?> +'<td>';
row_cusname.innerHTML = '<td id ="cusname" class="cusname">' + <?= data[i][2] ?> +'<td>';
row_pic.innerHTML = '<td id ="cic" class="cic">' + <?= data[i][3] ?> +'<td>';
row_remarks.innerHTML = '<td id ="remarks" class="remarks">' + <?= data[i][4] ?> +'<td>';
row_status.innerHTML = '<td id ="status" class="status">' +<?= data[i][5] ?> +'<td>';
row_docudate.innerHTML = '<td id ="docdate" class="docdate">'+ <?= data[i][6] ?> +'<td>';
row_button.innerHTML = '<td><img id = "selectdata" class = "click-to-select" src="https://docs.google.com/uc?id=0By6kUPbaVMWCbUI0LTJTR2g2N3M" alt="Submit" width="13px" height="13px" title = "Edit Selected Data" data-toggle="modal" data-target="#myModal"/></td>';
<? } ?>
}
</script>
and this is my table where i put the data based on code above.
<table id = "TableContainer" cellspacing="2" cellpadding="3" width ="100%" align = "center" class="hoverTable">
<tr>
<th bgcolor = "darkgreen"><font color="white">#</font></th>
<th bgcolor = "darkgreen"><font color="white">Area</font></th>
<th bgcolor = "darkgreen" width = "200px"><font color="white">Customer Name</font></th>
<th bgcolor = "darkgreen"><font color="white">Person In Charge</font></th>
<th bgcolor = "darkgreen" width = "250px"><font color="white">Remarks</font></th>
<th bgcolor = "darkgreen"><font color="white">Status</font></th>
<th bgcolor = "darkgreen"><font color="white">Doc. Date</font></th>
<th bgcolor = "darkgreen"></th>
</tr>
<tr>
</tr>
</table>
Please bear with me. this code is perfectly running and im running the code by '<body onLoad = "GenerateTable()"> how ever as what you see on my code there is a code that looks like this.
<td><img id = "selectdata" class = "click-to-select" src="https://docs.google.com/uc?id=0By6kUPbaVMWCbUI0LTJTR2g2N3M" alt="Submit" width="13px" height="13px" title = "Edit Selected Data" data-toggle="modal" data-target="#myModal"/></td>';
now it will create an image button for every row in my table and that code has a purpose and that is to transfer the data from td to textbox and other elements and here is my code for that.
<script>
$('.click-to-select').click(function() {
var dataid = $(this).closest('tr').find('td.dataid').text();
var area = $(this).closest('tr').find('td.area').text();
var cusname = $(this).closest('tr').find('td.cusname').text();
var cicoption = $(this).closest('tr').find('td.cic').text();
var remarks = $(this).closest('tr').find('td.remarks').text();
var statoption = $(this).closest('tr').find('td.status').text();
var documentdate = $(this).closest('tr').find('td.docdate').text();
$('#dataid').val(dataid)
$('#areaoption').val(area)
$('#cusname').val(cusname)
$('#cicoption').val(cicoption)
$('#remarks').val(remarks)
$('#statoption').val(statoption)
$('#documentdate').val(documentdate)
});
</script>
this is where the error starts when im clicking the image the row data is not transferring in my textbox whats the error?
Updated Code
<script>
function GenerateTable() {
<? var data = getData(); ?>
var table = document.getElementById("TableContainer");
<? for (var i = 12; i < data.length; i++) { ?>
var row = table.insertRow(-1);
var row_did = row.insertCell(0);
var row_area = row.insertCell(1);
var row_cusname = row.insertCell(2);
var row_pic = row.insertCell(3);
var row_remarks = row.insertCell(4);
var row_status = row.insertCell(5);
var row_docudate = row.insertCell(6);
var row_button = row.insertCell(7);
row_did.innerHTML = '<td id="dataid" class="dataid">'+ <?= data[i][0] ?> + '</td>';
row_area.innerHTML = '<td id="area" class="area">'+ <?= data[i][1] ?> +'<td>';
row_cusname.innerHTML = '<td id ="cusname" class="cusname">' + <?= data[i][2] ?> +'<td>';
row_pic.innerHTML = '<td id ="cic" class="cic">' + <?= data[i][3] ?> +'<td>';
row_remarks.innerHTML = '<td id ="remarks" class="remarks">' + <?= data[i][4] ?> +'<td>';
row_status.innerHTML = '<td id ="status" class="status">' +<?= data[i][5] ?> +'<td>';
row_docudate.innerHTML = '<td id ="docdate" class="docdate">'+ <?= data[i][6] ?> +'<td>';
row_button.innerHTML = '<td><img id = "selectdata" class = "click-to-select" src= "https://docs.google.com/uc?id=0By6kUPbaVMWCbUI0LTJTR2g2N3M" alt="Submit" width="13px" height="13px" title = "Edit Selected Data" data-toggle="modal" data-target="#myModal"/></td>';
<? } ?>
$('.click-to-select').click(function() {
var dataid = $(this).closest('tr').find('td.dataid').text();
var area = $(this).closest('tr').find('td.area').text();
var cusname = $(this).closest('tr').find('td.cusname').text();
var cicoption = $(this).closest('tr').find('td.cic').text();
var remarks = $(this).closest('tr').find('td.remarks').text();
var statoption = $(this).closest('tr').find('td.status').text();
var documentdate = $(this).closest('tr').find('td.docdate').text();
$('#dataid').val(dataid)
$('#areaoption').val(area)
$('#cusname').val(cusname)
$('#cicoption').val(cicoption)
$('#remarks').val(remarks)
$('#statoption').val(statoption)
$('#documentdate').val(documentdate)
});
}
</script>
TYSM
Could you put your second script $('.click-to-select').click(function(){...}) inside of GenerateTable() and after the for loop? Then check if the click handler is running by putting console.log('The dataid is:' + dataid) in here.
$('.click-to-select').click(function(){...
...
var documentdate = $(this).closest('tr').find('td.docdate').text();
console.log('The dataid is:' + dataid)
$('#dataid').val(dataid)
...
}
I can't tell for sure the order that your code executes because you have two separate script tags here, but it's possible your second script can't bind the click handler because the .click-to-selects haven't been created yet by GenerateTable().
Here is a working fiddle using nth-of-type selectors
First you need to remove the id from td because some of it matches with textbox element.
Then replace it with below line of code and do the same for each column.
var dataid = $(this).parent().siblings('.dataid').text();
I think , This function should be like below
Don't use the php tags because these are javascript variables .
function GenerateTable() {
var data = getData();
var table = document.getElementById("TableContainer");
for (var i = 12; i < data.length; i++) {
var row = table.insertRow(-1);
var row_did = row.insertCell(0);
var row_area = row.insertCell(1);
var row_cusname = row.insertCell(2);
var row_pic = row.insertCell(3);
var row_remarks = row.insertCell(4);
var row_status = row.insertCell(5);
var row_docudate = row.insertCell(6);
var row_button = row.insertCell(7);
row_did.innerHTML = '<td id="dataid" class="dataid">'+ data[i][0] + '</td>';
row_area.innerHTML = '<td id="area" class="area">'+ data[i][1] +'<td>';
row_cusname.innerHTML = '<td id ="cusname" class="cusname">' + data[i][2] +'<td>';
row_pic.innerHTML = '<td id ="cic" class="cic">' + data[i][3] +'<td>';
row_remarks.innerHTML = '<td id ="remarks" class="remarks">' + data[i][4] +'<td>';
row_status.innerHTML = '<td id ="status" class="status">' + data[i][5] +'<td>';
row_docudate.innerHTML = '<td id ="docdate" class="docdate">'+ data[i][6] +'<td>';
row_button.innerHTML = '<td><img id = "selectdata" class = "click-to-select" src= "https://docs.google.com/uc?id=0By6kUPbaVMWCbUI0LTJTR2g2N3M" alt="Submit" width="13px" height="13px" title = "Edit Selected Data" data-toggle="modal" data-target="#myModal"/></td>';
}
$('.click-to-select').click(function() {
var dataid = $(this).closest('tr').find('td.dataid').text();
var area = $(this).closest('tr').find('td.area').text();
var cusname = $(this).closest('tr').find('td.cusname').text();
var cicoption = $(this).closest('tr').find('td.cic').text();
var remarks = $(this).closest('tr').find('td.remarks').text();
var statoption = $(this).closest('tr').find('td.status').text();
var documentdate = $(this).closest('tr').find('td.docdate').text();
$('#dataid').val(dataid)
$('#areaoption').val(area)
$('#cusname').val(cusname)
$('#cicoption').val(cicoption)
$('#remarks').val(remarks)
$('#statoption').val(statoption)
$('#documentdate').val(documentdate)
});
}
Hopefully , it may help you .

onclick an a specific checkbox display a buttton.js hquery

I have a dynamic table with checkboxes. I was trying to display a button onlick of a particular checkboxes, currently the button is displaying but only for the first checkboxes, its not working for the remaining checkboxes. I have my test code below please help me to display of a button on click of a particular checkboxes. help will be highly appreciated.[![enter image description here][1]][1]
//this is how i am creating a dynamic table with checkbox
var table = document.getElementById('testbody');
for (var i = 0; i < (test.length); i = i + 2) {
var row = tablebody.insertRow(-1);
var cell3 = row.insertCell(-1);
var cell1 = row.insertCell(-1);
var cell2 = row.insertCell(-1);
cell1.innerHTML = '<span style="font-size:20px;">'
+ test[i] + '</span>';//values from db
cell2.innerHTML = '<span style="font-size:20px;">'
+ test[i+1] + '</span>';//values form db
//this is my checkbox
cell3.innerHTML = '<input type="checkbox" id="your" value="yourCheckBoxVal">';
}
//this is how im trying to display a button
$(document).ready(function () {
$('#your').change(function () {
if (!this.checked)
alert("test1");
else
alert("test2");
}).change();
});
}
//this is just an eg:
<table id="testtablet" >
<thead>
<tr >
<td width="400px">
</td>
</tr>
</thead>
<tbody id="testbody"></tbody>
</table>
//this is the button i was trying to display
<button type="button" id="chochk" style="display:none" class="sukuti">event</button>
[1]:
IDs must be unique. Like suggested in the comment you can use your as a class.
You can attach the change event handler in a different way:
$('#testbody :checkbox.your').change(function (e) {
For dynamically added (in future, after the definition of change event handler) elements you can delegate the change event:
$('#testbody').on('change', ':checkbox.your', function (e) {
In order to toggle button visibility according to the checkbox state you can write:
$('#chochk').toggle(this.ckhecked);
$(document).ready(function () {
var test = ['06/12/2017', 'test', '06/13/2017', 'testing'];
var table = document.getElementById('testbody');
for (var i = 0; i < (test.length); i = i + 2) {
var row = table.insertRow(-1);
var cell3 = row.insertCell(-1);
var cell1 = row.insertCell(-1);
var cell2 = row.insertCell(-1);
cell1.innerHTML = '<span style="font-size:20px;">'
+ test[i] + '</span>';//values from db
cell2.innerHTML = '<span style="font-size:20px;">'
+ test[i + 1] + '</span>';//values form db
//this is my checkbox
cell3.innerHTML = '<input type="checkbox" class="your" value="yourCheckBoxVal">';
}
$('#testbody :checkbox.your').change(function (e) {
console.log("test: " + this.checked);
$('#chochk').toggle(this.ckhecked);
}).change();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="testtablet">
<thead>
<tr>
<td width="400px">
</td>
</tr>
</thead>
<tbody id="testbody"></tbody>
</table>
<button type="button" id="chochk" style="display:none" class="sukuti">event</button>
1) do not use same ID for more than one element
use class instead

How to convert HTML table to Javascript

So as a beginner, I have no idea how to create a table using Javascript. I can make a table using a simple html file but not in Javascript.
The output should have 2 columns and 4 rows. I also need to use the prompt tag in order to insert data for the second column. Not to mention that I need to average the total number in the 2nd column.
I tried searching but I got mixed results and its confusing me.so please help me
this is the html file
<html>
<body>
<table border="1" style="width:30%">
<tr>
<td>Rose</td>
<td>40</td>
</tr>
<tr>
<td>Daisy</td>
<td>50</td>
</tr>
<tr>
<td>Orchids</td>
<td>60</td>
</tr>
<tr>
<td>Flowers</td>
<td>150</td>
</tr>
</table>
</body>
</html>
Try this - >
var Rose = prompt("Enter price for Rose?");
var Daisy = prompt("Enter price for Daisy?");
var Orchids = prompt("Enter price for Orchids?");
var flowers = Number(Rose) + Number(Daisy) + Number(Orchids);
var table = document.createElement("table");
createTable();
function createTable(){
createTrTds("Rose",Rose);
createTrTds("Daisy",Daisy);
createTrTds("Orchids",Orchids);
createTrTds("Total",flowers);
document.getElementById("table").appendChild(table);
}
function createTrTds(text,value){
var tr = document.createElement("tr");
var td1 = document.createElement("td");
var td2 = document.createElement("td");
var txt1 = document.createTextNode(text);
var txt2 = document.createTextNode(value);
td1.appendChild(txt1);
td2.appendChild(txt2);
tr.appendChild(td1);
tr.appendChild(td2);
table.appendChild(tr);
}
td
{
border: 1px solid black;
}
<div id="table">
</div>
You will be helped by using a framework for this, jquery or angularjs comes to mind to solve it. However the pure JavaScript way looks like this:
This will create a table with inputs for the number of flowers and sum them up at the bottom when numbers change, you can also add more flower types in the JavaScript file.
var tabledef = [];
tabledef['Rose'] = 40;
tabledef['Daisy'] = 50;
tabledef['Orchids'] = 60;
writeTable();
function writeTable() {
var table = '<table border="1" style="width:30%">';
var sum = 0;
for (var i in tabledef) {
sum = sum + tabledef[i];
table = table + '<tr><td>' + i + '</td><td><input id="' + i + '" onchange="recalculate(this)" type="number" value="' + tabledef[i] + '"></td></tr>';
}
table = table + '<tr><td>Flowers</td><td>' + sum + '</td></tr></table>';
document.getElementById('myTable').innerHTML = table;
}
function recalculate(box) {
tabledef[box.id] = box.valueAsNumber;
writeTable();
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="myTable"></div>
<script src="createTable.js"></script>
</body>
</html>
You just need array with data and then fill table as thought it was an html document
var table = '<table border="1">',
data = [['Rose','Daisy','Orchids','Flowers'],[40,50,60,150]];
for (var i = 0; i < data[0].length; i++) {
table += '<tr>';
for (var j = 0; j < data.length; j++) {
table += '<td>' + data[j][i] + '</td>';
}
table += '</tr>';
}
table += '</table>';
document.getElementById('container').innerHTML = table;
http://jsfiddle.net/5pdac6sb/

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';

Categories

Resources