Create Rows in a Table using Javascript - adds too many cells...> - javascript

I'm trying to create a table on the fly... it almost works but I have an issue with the number of cell it adds.
My table has 8 columns (monday to Friday plus a total column at the end).
Here is the fiddle for it: http://jsfiddle.net/kaf9qmh0/
As you can see, on row 1, it adds the 8 columns 3 times, then on row 2 it adds the columns twice and only on the last row does it only add 8 columns.
I suspect it is because Im using .append to add the rows as follows (line 105 in the fiddle) but my Javascript being very limited, Im not entirely sure how to make it stop add the columns to row 1 and 2.
$("#timesheetTable > tbody").append('<tr id="' + sourceTableRowID + '" data-tt-id="' + sourceTableRowID + '" class="timesheetRow row' + rowIndex2 + '"></tr>');
How can I make it to only add the cells (td) to the next row when it loops through rowIndex2 and increments it?
Can somebody point me in the right direction please?

You had a loop within a loop - which was causing the additional cells. Here's an updated fiddle; and here's an extract of the modified code:
function createSampleRows() {
var sourceTable = document.getElementById('activityTable');
var sourceTableRows = sourceTable.rows.length;
var targetTable = document.getElementById('timesheetTable');
var rowindex;
var targetTableColCount;
for (var rowIndex = 0; rowIndex < targetTable.rows.length; rowIndex++) {
if (rowIndex == 1) {
targetTableColCount = targetTable.rows.item(rowIndex).cells.length;
continue; //do not execute further code for header row.
}
}
for (rowIndex = 0; rowIndex < (parseInt(sourceTableRows)-2); rowIndex++) {
var sourceTableRowID = document.getElementsByClassName('activityTaskRow')[rowIndex].id;
$("#timesheetTable > tbody").append('<tr id="' + sourceTableRowID + '" data-tt-id="' + sourceTableRowID + '" class="timesheetRow row' + rowIndex + '"></tr>');
};
// This loop was nested within the above loop
for (x = 0; x < targetTableColCount; x++) {
$("#timesheetTable > tbody > tr").append('<td id="' + x + '" style="width: 60px;height: 34px;" class=""></td>');
};
};

Related

How to get id of a element in all the rows of a table using jQuery

My table id is "termTable". I am iterating through each row of the table. The id of textbox is "label'+ i +'" since I used for loop to generate ids randomly. The values of i will be unordered maybe after adding the rows or deleting the rows. Example: IDs are label1, label2, label3. After deleting the 2nd row, I am adding another row. So now the IDs are label1,label3, label4. I want to retrieve all the ids of all the textbox elements. How can I achieve it? Please help.
for (var i = 0; i < firstTabLength; i++) {
var row = $("#termTable tr").eq(i);
var id = row.find('input[type="text"]').attr('id'); // I could see id = undefined
}
This is Html. This is for adding the new rows to table. Guess you can visualize the table structure with the help of below code.
function AddCustomTerm1() {
len = len + 1;
var table = document.getElementById("termTable");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML = '<input type="text" class="form-control" id="label' + (len - 1) + '" name="label' + (len - 1) + '" value=""><input type="hidden" id="step' + (len - 1) + '" value="1"/>';
row.insertCell(1).innerHTML = '<select class="form-control" id="dataTypes' + (len - 1) + '" name="dataTypes' + (len - 1) + '" onchange="changeDataType(this)"></select>'
row.insertCell(2).innerHTML = '<input type="text" class="form-control" id="ContractTerm' + (len - 1) + '" name="ContractTerm' + (len - 1) + '" value="">';
var DD = document.getElementById("dataTypes" + (len - 1));
for (var i = 0; i < datatypesarray.length; i++) {
var opt = document.createElement("option");
opt.text = datatypesarray[i];
opt.value = datatypesarray[i];
DD.appendChild(opt);
}
without you html format cant help much.
but try this ones.you dont even need a for loop to get all the textbox and their ids from table.
var ids=[];
$('#termTable input[type="text"]').each(function(){
ids.push($(this).attr('id'))
})
if you want ids of the textboxes in first column of the table.the try this
var ids=[];
$('#termTable tr').each(function(){
ids.push($(this).find('td:first-child input[type="text"]').attr('id'))
})
The best practice is to add a specific class to all of your elements that need to be iterated.
For example add the class term-table-input to your inputs:
row.insertCell(0).innerHTML = '<input type="text" class="form-control term-table-input" id="label' + (len - 1) + '" name="label' + (len - 1) + '" value=""><input type="hidden" id="step' + (len - 1) + '" value="1"/>';
And iterate them with:
var termTableInputIDs = [];
$('.term-table-input').each(function () {
termTableInputIDs.push($(this).attr('id'));
});
Also you could read more about writing efficient css here:
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Writing_efficient_CSS
Since you have more than one input[type="text"] in a row, you should take the first. Also you can use each() instead of for.
$('#termTable tr').each(function() {
var id = $(this).find('input[type="text"]:first').attr('id');
console.log(id);
});
You find all the input elements inside the table by using $('#termTable input') and to loop through all the selected elements you use $.each API
Use Code like below.
var InputIds = []; //array to hold your id's
$.each($('#termTabel input[type="text"]'),function(i,v){
InputIds.push($(this).attr('id'));
});
console.log(InputIds.toString());
//this finds all inputs which id start from "label"
$('#termTable input[id^="label"]').each(function(){ console.log(this.id); });
example: https://jsbin.com/lisuratere/edit?html,js,output

After deletion changing id of textbox inside cell id not working

I have table using Javascript and I am deleting the rows using a delete function
After the deletion I am trying to reindex the table cell ids
function updateRowCount(){
var table = document.getElementById("ordertable");
var rowcountAfterDelete = document.getElementById("ordertable").rows.length;
for(var i=1;i<rowcountAfterDelete;i++){
table.rows[i].id="row_"+i;
table.rows[i].cells[0].innerHTML=i+"<input type='checkbox' id='chk_" + i + "'>";
table.rows[i].cells[1].id="notes_"+i;
table.rows[i].cells[2].id="amount"+i;
}
}
But the following lines not working:
table.rows[i].cells[1].id="notes_"+i;
table.rows[i].cells[2].id="amount"+i;
<td>'s contains input boxes, it will be like this
<td><input type="text" title="notes"></td>
<td><input type="text" title="amount"></td>
How can I change the id of text box inside <td> or cell ?
I made a jsfiddle here https://jsfiddle.net/an87ka5p/
I updated this to answer the question in the comments
function test() {
var table = document.getElementById("ordertable");
var rowcountAfterDelete = table.rows.length;
for (var i = 0; i < rowcountAfterDelete; i++) {
table.rows[i].id = "row_" + i;
table.rows[i].cells[0].innerHTML = i + "<input type='checkbox' id='chk_" + i + "'>";
table.rows[i].cells[1].getElementsByTagName("input")[0].id = "notes_" + i;
table.rows[i].cells[2].getElementsByTagName("input")[0].id = "amount_" + i;
}
}

How to make list in jQuery mobile nested list?

Can you please tell me how to make list in jQuery mobile? I am trying to make this type list as given in fiddle on pop up screen dynamically .
Here is the fiddle
In this fiddle I make two rows.In first row there is only p tag. But in second row there is nested collapsible rows. I need to make same thing in pop up screen. I am able to make first row. But In my second row contend is null why? Can you suggest where I am wrong?
fiddle
$(function () {
$('#test').click(function(){
alert('d');
createCommandPopUpTabs();
$("#tabbedPopup").popup("open");
});
});
var tabsHeader = [ "InputParameter", "basic"];
var tabsHeader_basic = [ "XYZ", "Third Level",
];
function createCommandPopUpTabs(){
var header = "<h3 >dd</h3>";
var commmand = 'dd';
var button = '<button onclick="return submitCommand("'+
'")" style="" class="donebtn common-button1">Save</button>';
$("#commandInfo").append(button);
$("#commandInfoheader").html(header);
for ( var i = 0; i < tabsHeader.length; i++) {
var headerId = tabsHeader[i] + "_tab" + commmand;
var header = "<div data-role='collapsible' data-collapsed='false' id='"
+ headerId + "'><h3>InputParameter</h3></div>";
var content ;
if(tabsHeader[i]=="InputParameter"){
content = "<p>yes</p>";
}else if(tabsHeader[i]=="basic"){
for ( var i = 0; i < tabsHeader_basic.length; i++) {
headerId = tabsHeader_basic[i] + "_tab" + commmand;
header = "<div data-role='collapsible' data-collapsed='false' id='"
+ headerId + "'><h3>basic</h3></div>";
content += getcontend(tabsHeader_basic[i]);
}
}
$("#tabbedSet").append(header);
$("#tabbedSet").find("#" + headerId).append(content);
$("#tabbedSet").collapsibleset("refresh");
}
}
function getcontend(name){
if(name=="Third Level"){
return"<p>Third Level></p>";
} if(name=="XYZ"){
return"<p> second Level></p>";
}
}
There are errors in your code and logic. I will only go over a couple of them to hopefully get you on the right path:
In tabsHeader_basic array the Third Level has a space in it which you later use as an ID which makes it an invalid ID because you cannot have spaces in an ID.
From the HTML 5 Draft:
The value must not contain any space characters.
Also, the "basic" collapsible div needs to exist before you start adding the nested collapsible div.
So this line needs to come out of the for loop
header = "<div data-role='collapsible' data-collapsed='false' id='"+ headerId + "'><h3>basic</h3></div>";
Go through the JSFiddle and compare your code agaisnt my changes.
Hopefully that helps! Let me know if you have any other questions.
I have updated createCommandPopUpTabs() function.
Also removed space in Third Level on var tabsHeader_basic = ["XYZ", "ThirdLevel"];
Check the Updated Fiddle
function createCommandPopUpTabs() {
var header = "<h3 >dd</h3>";
var commmand = 'dd';
var button = '<button onclick="return submitCommand("' +
'")" style="" class="donebtn common-button1">Save</button>';
$("#commandInfo").html(button);
$("#commandInfoheader").html(header);
$("#tabbedSet").html('');
for (var i = 0; i < tabsHeader.length; i++) {
var headerId = tabsHeader[i] + "_tab" + commmand;
var header = "<div data-role='collapsible' data-collapsed='true' id='" + headerId + "'><h3>" + tabsHeader[i] + "</h3></div>";
$("#tabbedSet").append(header);
var content;
if (tabsHeader[i] == "InputParameter") {
content = "<p>yes</p>";
$("#tabbedSet").find("#" + headerId).append(content);
} else if (tabsHeader[i] == "basic") {
for (var j = 0; j < tabsHeader_basic.length; j++) {
var headerId1 = tabsHeader_basic[j] + "_tab" + commmand;
var header1 = "<div data-role='collapsible' data-collapsed='true' id='" + headerId1 + "'><h3>" + tabsHeader_basic[j] + "</h3></div>";
var content1 = getcontend(tabsHeader_basic[j]);
$("#tabbedSet").find("#" + headerId).append(header1);
$("#tabbedSet").find("#" + headerId1).append(content1);
}
}
$("#tabbedSet").collapsibleset("refresh");
}
}

Creating html table using Javascript not working

Basically, I want the user the just change the 'height' variable to how ever many rows he wants, and then store the words which each td in the row should contain, and the code should then generate the table.
My html is just this:
<table id="newTable">
</table>
This is my Javascript:
<script type="text/javascript">
var height = 2; // user in this case would want 3 rows (height + 1)
var rowNumber = 0;
var height0 = ['HeadingOne', 'HeadingTwo']; // the words in each td in the first row
var height1 = ['firstTd of row', 'secondTd of row']; // the words in each td in the second row
var height2 = ['firstTd of other row', 'secondTd of other row']; // the words in each td in the third row
$(document).ready( function() {
createTr();
});
function createTr () {
for (var h=0; h<height + 1; h++) { // loop through 3 times, in this case (which h<3)
var theTr = "<tr id='rowNumber" + rowNumber + "'>"; // <tr id='rowNumber0'>
$('#newTable').append(theTr); // append <tr id='rowNumber0'> to the table
for (var i=0; i<window['height' + rowNumber].length; i++) {
if (i == window['height' + rowNumber].length-1) { // if i==2, then that means it is the last td in the tr, so have a </tr> at the end of it
var theTd = "<td class='row" + rowNumber + " column" + i + "'>" + window['height' + rowNumber][i] + "</td></tr>";
$('#rowNumber' + rowNumber).append(theTr); // append to the end of the Tr
} else {
var theTd = "<td class='row" + rowNumber + " column" + i + "'>" + window['height' + rowNumber][i] + "</td>";
$('#rowNumber' + rowNumber).append(theTr);
}
}
rowNumber += 1;
}
}
</script>
I did 'alert(theTr);' and 'alert(theTd);' and they looked correct. How come this code doesn't generate any table?
You should change the line
$('#rowNumber' + rowNumber).append(theTr);
into
$('#rowNumber' + rowNumber).append(theTd);
You are adding the Tr-Code again in the inner loop, but you actually wanted to add the Td-Code.
All that window["height"+rowNumber] stuff is a poor way to do it. Use an array, and pass it as a parameter to the function so you don't use global variables. And use jQuery DOM creation functions instead of appending strings.
<script type="text/javascript">
var heights = [['HeadingOne', 'HeadingTwo'], // the words in each td in the first row
['firstTd of row', 'secondTd of row'], // the words in each td in the second row
['firstTd of other row', 'secondTd of other row'] // the words in each td in the third row
];
$(document).ready( function() {
createTr(heights);
});
function createTr (heights) {
for (var h=0; h<heights.length; h++) { // loop through 3 times, in this case (which h<3)
var theTr = $("<tr>", { id: "rowNumber" + h});
for (var i=0; i<heights[h].length; i++) {
theTr.append($("<td>", { "class": "row"+h + " column"+i,
text: heights[h][i]
}));
}
$('#newTable').append(theTr); // append <tr id='rowNumber0'> to the table
}
}
</script>
JSFIDDLE

How to find empty tr in table using Javascript [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to find Empty tr in table, is there any way to find it?
after finding empty row I want to insert some data in it.
Supposing you have this HTML :
<table id=tbl>
<tr><td>A</td><td>B</td></tr>
<tr><td>A</td><td>B</td></tr>
<tr><td></td><td></td></tr> <!-- this line is empty -->
<tr><td>A</td><td>B</td></tr>
</table>
Then you can fill the empty line like this :
var rows = document.getElementById('tbl').rows;
for (var i=0; i<rows.length; i++) {
var txt = rows[i].textContent || rows[i].innerText;
if (txt.trim()==="") rows[i].innerHTML="<td>Something</td>";
}
Demonstration
This uses :
the rows property of the table
textContent (or innerText for IE) to get the content without the tags
As this also use the trim function which isn't available in IE8, you might want to add this shim :
if(!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g,'');
};
}
There might be better ways, this is what occurred to me.
$('tr').each(function() {
if($(this).find('td').length == 0) {
// empty tr
// id of tr is available through this.id
}
});
Maybe something like this $('table tr:empty').html('....')
var tables = document.getElementsByTagName('table');
var table = tables[0];
var trs = table.getElementsByTagName('tr');
for (var i = 0; i < trs.length; i++) {
if (trs[i].innerHTML === '') {
console.log('EMPTY', trs[i]);
} else {
console.log('NOT EMPTY', trs[i]);
}
}
I think its not easy. You can see this link.
HTML:
<table id="table" style="border: 1px solid green;"><tbody>
<tr id="empty"></tr>
<tr id="withText"><font style="color: red;">text</font></tr>
<tr id="withEmptyTd"><td></td></tr>
<tr id="withTdWithText"><td>text</td></tr>
</tbody></table>
<div id="output"></div>
Javascript:
var output = document.getElementById('output');
var table = document.getElementById('table');
var trs = table.querySelectorAll('tr');
var tr, id, text, tds, j, td, tdText;
for (var i = 0; i < trs.length; i++) {
tr = trs[i];
id = tr.id;
output.innerHTML += "Getting tr[" + id + "]<br />";
text = tr.innerHTML;
output.innerHTML += "tr[" + id + "].innerHTML = \"" + text + "\" it's length = " + text.length + "<br />";
tds = tr.querySelectorAll('td');
output.innerHTML += "tr[" + id + "] have " + tds.length + " tds<br />";
for (j = 0; j < tds.length; j++) {
td = tds[j];
tdText = td.innerHTML;
output.innerHTML += "tr[" + id + "] -> td[" + j + "].innerHTML = \"" + tdText + "\" its length = " + tdText.length + "<br />";
}
}
And output will be:
Getting tr[empty]
tr[empty].innerHTML = "" it's length = 0
tr[empty] have 0 tds
Getting tr[withText]
tr[withText].innerHTML = "" it's length = 0
tr[withText] have 0 tds
Getting tr[withEmptyTd]
tr[withEmptyTd].innerHTML = "" it's length = 9
tr[withEmptyTd] have 1 tds
tr[withEmptyTd] -> td[0].innerHTML = "" its length = 0
Getting tr[withTdWithText]
tr[withTdWithText].innerHTML = "text" it's length = 13
tr[withTdWithText] have 1 tds
tr[withTdWithText] -> td[0].innerHTML = "text" its length = 4
Cause any tag or text in tr but not in td shows before the table.

Categories

Resources