After deletion changing id of textbox inside cell id not working - javascript

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

Related

How to increment an array with each dynamically created table row in JavaScript

I'm dynamically creating rows in a table with 3 columns: Item, Description & QTY. How do I increment an array with each dynamically created table row?
Here's the results I'm getting when submitting the form below containing two rows with the following values.
The first row values are: Item1, Description1, Qty1
and the second row values are: Item2, Description2, Qty2
1=Item1&1=Description1&1=QTY1&1=Item2&1=Description2&1=QTY2
I would like to return the following instead:
1=Item1&1=Description1&1=QTY1&2=Item2&2=Description2&2=QTY2
https://jsfiddle.net/rimshot609/zgdvxo83/4/
<form name="SiteForm" id="SiteForm" method="post" action="mailto:test#test.com">
<div class="line-item">
<fieldset>
<table id="textbox" border="0">
<tbody>
<tr>
<td>
</td>
</tr>
</tbody>
</table>
<input type="itembutton" onclick="createTableRows()" value="Add Item" />
</fieldset>
</div>
<input type="submit" name="subform" value="Submit Form" />
<script>
function createTableRows() {
var someText = 'Item, Name, Qty,'
var table = document.getElementById("textbox");
var rowlen = table.rows.length;
var row = table.insertRow(rowlen);
row.id = rowlen;
for (i = 0; i < 2; i++) {
arr = ['1']; //I need this number to increase by 1 with each table row created.
var x = row.insertCell(i)
if (i == 1) {
x.innerHTML = "<input type='button' onclick='removeCell(" + row.id + ")' value=Delete>"
} else {
x.innerHTML = "<input type='textbox' placeholder='Item Number' name='" + arr[i] + "' required='required'><input type='textbox' placeholder='Description' name='" + arr[i] + "' required='required'><input type='textbox' placeholder='QTY' name='" + arr[i] + "' required='required'>"
}
}
}
function removeCell(rowid) {
var table = document.getElementById(rowid).remove();
}
</script>
</form>
Without deletion, it's very simple. Just replace this line:
arr = ['1']; //I need this number to increase by 1 with each table row created.
With this:
arr = [row.id]; //I need this number to increase by 1 with each table row created.
row.id is always set to table.rows.length.
But when you introduce Deletion into the equation things get more complicated. Each time you delete a row you'll want to either change the value for the existing rows, or use another value that you increment differently.
The first solution feels quite elegant, but with the way this has been set up would be a little clunky to implement. The other would require something like:
let highestValue = 0;
function createTableRows() {
highestValue++;
var someText = 'Item, Name, Qty,'
var table = document.getElementById("textbox");
var rowlen = table.rows.length;
var row = table.insertRow(rowlen);
row.id = highestValue;
The problem is that you'll have gaps. If you have rows 1, 2 and 3 then delete 2, the results will jump from 1 to 3.

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

Display the checkboxes selected into a section and the unselected into another one

I want to show the checkboxes selected into a div but actually I have a duplicate item in the list and I'm not sure how to display the unselected items into another div.
You can try out here http://jsfiddle.net/tedjimenez/7wzR5/
Here my code:
JS CODE
/* Array */
var list = new Array("valuetext000", "valuetext001", "valuetext002", "valuetext003", "valuetext004", "valuetext005", "valuetext006", "valuetext007", "valuetext008", "valuetext009", "valuetext010", "valuetext011", "valuetext012", "valuetext013", "valuetext014", "valuetext015", "valuetext016", "valuetext017")
var html = "";
/* Array will be converted to an ul list */
for (var i = 0; i < list.length; i++) {
html += "<input type='checkbox' name='boxvalue' value='" + list[i] + "' /><label>" + list[i] + "</label><br>";
}
$("#elmAv").append(html);
THE HTML CODE
<form>
<div id="elmAv"></div>
<div id="selectionResult"></div>
<script>
/* Function to display the items selected */
function showBoxes(frm) {
var checkedItems = "\n";
//For each checkbox see if it has been checked, record the value.
for (i = 0; i < frm.boxvalue.length; i++) {
if (frm.boxvalue[i].checked) {
checkedItems = checkedItems + "<li>" + frm.boxvalue[i].value + "<li>";
}
}
$("#elmAv").empty();
$("#selectionResult").append(checkedItems);
}
</script>
<input type="Button" value="Get Selection" onClick="showBoxes(this.form)" />
</form>
Simply add another div after selectionResult like this:
<div id="unselectedResult"></div>
And then update showBoxes() with the following code:
function showBoxes(frm) {
var checkedItems = "Checked:<br>\n";
var uncheckedItems = "Unchecked:<br>\n";
//For each checkbox see if it has been checked, record the value.
for (i = 0; i < frm.boxvalue.length; i++) {
if (frm.boxvalue[i].checked) {
checkedItems = checkedItems + "<li>" + frm.boxvalue[i].value + "</li>";
}
else {
uncheckedItems = uncheckedItems + "<li>" + frm.boxvalue[i].value + "</li>";
}
}
$("#elmAv").empty();
$("#selectionResult").append(checkedItems);
$('#unselectedResult').append(uncheckedItems);
}
Should get the result you're looking for.
This should work. Added another array listChecked to track checked values.
<script>
/* Array */
var list = new Array("valuetext000", "valuetext001", "valuetext002", "valuetext003", "valuetext004", "valuetext005", "valuetext006", "valuetext007", "valuetext008", "valuetext009", "valuetext010", "valuetext011", "valuetext012", "valuetext013", "valuetext014", "valuetext015", "valuetext016", "valuetext017")
var listChecked = new Array();
$(document).ready(function() {
displayUnchecked();
});
/* Array will be converted to an ul list */
function displayUnchecked()
{
var html = "";
for (var i = 0; i < list.length; i++) {
if ($.inArray(list[i], listChecked) == -1)
html += "<input type='checkbox' name='boxvalue' value='" + list[i] + "' /><label>" + list[i] + "</label><br>";
}
$("#elmAv").html(html);
}
</script>
</head>
<body>
<form>
<div id="elmAv"></div>
<div id="selectionResult"></div>
<script>
/* Display the items selected */
function showBoxes(frm) {
var checkedItems = "\n";
//alert('here');
//For each checkbox see if it has been checked, record the value.
for (i = 0; i < frm.boxvalue.length; i++) {
if (frm.boxvalue[i].checked) {
listChecked.push(frm.boxvalue[i].value);
}
}
$.each(listChecked, function (index, value)
{
checkedItems = checkedItems + "<li>" + value + "</li>";
});
//alert('here');
displayUnchecked();
//$("#elmAv").empty();
$("#selectionResult").html(checkedItems);
}
</script>
<input type="Button" value="Get Selection" onClick="showBoxes(this.form)" />
</form>
</body>

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 call to a function, with a string

i am creating a string from all the headlines of a table, that making a checkbox to each headline, and its should hide the col if its unchecked and show if its checked.
the function put all the checkbox in a div.
i am calling the function when the page is loaded (onload in the body)
this is my function:
function getFirstRow(table) {
var table = document.getElementById(table);
var row = table.getElementsByTagName('tr')[0];
var cells = row.getElementsByTagName('th');
var str = "";
for (var i=0; i < cells.length; i++) {
str += "<input type='checkbox' onclick='hideOrShowCol('TreesTable', "+i+", this);' checked='checked' />" + cells[i].innerHTML + " ";
}
document.getElementById("hideAndShow").innerHTML = str;
}
and this is the hide/show function:
function hideOrShowCol(table, col, e) {
alert(e.checked);
var ifToShow = "";
if (e.checked)
ifToShow = "table-cell";
else
ifToShow = "none";
var getTable = document.getElementById(table);
var tds = getTable.getElementsByTagName("tr");
for (var i = 0; i < tds.length; i++) {
tds[i].childNodes[col].style.display = ifToShow;
}
}
so the problem is that it is not calling to the function when i am creating the check boxes with the first function, but when i am writing directly in the html its works fine, like this:
<input type="checkbox" onclick="hideOrShowCol('TreesTable', 2, this);" checked="checked" />
some one know what its can be?? i tried everything...
thanks.
"<input type='checkbox' onclick='hideOrShowCol('TreesTable', "+i+", this);' checked='checked' />" is invalid because of the single quotes areound 'TreesTable' nested inside the single quote for the onclick.
Try changing to "<input type='checkbox' onclick='hideOrShowCol(\"TreesTable\", "+i+", this);' checked='checked' />"
try closing over 'i' and passing it to an anonymous self-invoking function:
for (var i=0; i < cells.length; i++) {
(function(indx) {
str += "<input type='checkbox' onclick='hideOrShowCol('TreesTable', "+indx+", this);' checked='checked' />" + cells[indx].innerHTML + " ";
})(i);
}

Categories

Resources