FInd a control s value inside a table in tr - javascript

I have this table and I want to find a hidden control's value inside the tr .
I tried this javascript
function DeleteGridview_Row(pid) {
alert(pid);
var table = document.getElementById('<%= gvResults_gov.ClientID %>');
rows = table.getElementsByTagName('tr');
var i;
var j;
var cells;
var customerId;
for (i = 0, j = rows.length; i < j; ++i) {
cells = rows[i].getElementsByTagName('td');
if (!cells.length) {
continue; }
customerId = cells[0].innerHTML;
}
alert(customerId);
}
HTML
<table cellpadding="4" style="color: #333333; border-width: 0px; border-style: Groove;
width: 100%; font-weight: bold; width: 100%;" id="MainContent_gvResults_gov"
class="box-table-b">
<tbody>
<tr >
<td>
<input type="hidden" value="6532" id="MainContent_gvResults_gov_hdDocID_0" name="ctl00$MainContent$gvResults_gov$ctl02$hdTocID">
</td>
<td>
1010041215
</td>
</tr>
</tbody>
</table>

remove the enter code here
if the code is complete you need an ending }
If the customer ID is 1010041215 you need the second cell (from 0)
for (i = 0, j = rows.length; i < j; ++i) {
cells = rows[i].getElementsByTagName('td');
if (!cells.length) {
continue; }
customerId = cells[1].innerHTML; // [1] is the second cell
}
}
change
customerId = cells[1].innerHTML; // [1] is the second cell
to
customerId = cells[1].getElementsByTagName("input")[0].value
if you want the value of the input field
However tables have rows and cells:
function DeleteGridview_Row(pid) {
var customerId = "";
var table = document.getElementById('<%= gvResults_gov.ClientID %>');
var rows = table.rows;
for (i = 0, n = rows.length; i < n; ++i) {
cells = rows[i].cells;
if (!cells.length) {
continue; }
customerId = cells[1].innerHTML;
}
}
return customerId;
}

Related

How to delete table cells properly

I am trying to delete table rows and table column. For that i have written two functions. The DelelteRow() and DeleteColumn() delete the cells which have
index greater then zero. But actually one row or column should be deleted at a time. can some one modify my code.
DeleteRow:
function DeleteRows() {
var tbl = document.getElementById('myTable'),
lastRow = tbl.rows.length - 1,
i;
for (i = lastRow; i > 0; i--) {
tbl.deleteRow(i);
}
}
DeleteColumn:
function DeleteColumns() {
var tbl = document.getElementById('myTable'),
lastCol = tbl.rows[0].cells.length - 1,
i, j;
for (i = 0; i < tbl.rows.length; i++) {
for (j = lastCol; j > 0; j--) {
tbl.rows[i].deleteCell(j);
}
}
Something like this will delete one row/column at a time. Your question is not entirely clear which row/column you'd like removed, but your code implies you only want the last row/column removed.
var delRowBtn = document.querySelector('.delRow');
delRowBtn.addEventListener('click', deleteLastRow);
var delColBtn = document.querySelector('.delCol');
delColBtn.addEventListener('click', deleteLastColumn);
var tbl = document.querySelector('table');
function deleteLastRow() {
tbl.deleteRow(tbl.rows.length - 1);
}
function deleteLastColumn() {
var lastCol = tbl.rows[0].cells.length - 1;
for (var i = 0; i < tbl.rows.length; i++) {
tbl.rows[i].deleteCell(lastCol);
}
}
html, body {
font-size: 24px;
}
table {
margin-top: 30px;
}
td {
padding: 10px;
outline: 1px solid lightgrey;
}
<button class="delRow">Delete Row</button>
<button class="delCol">Delete Column</button>
<table>
<tbody>
<tr>
<td>r0c0</td>
<td>r0c1</td>
<td>r0c2</td>
<td>r0c3</td>
<td>r0c4</td>
</tr>
<tr>
<td>r1c0</td>
<td>r1c1</td>
<td>r1c2</td>
<td>r1c3</td>
<td>r1c4</td>
</tr>
<tr>
<td>r2c0</td>
<td>r2c1</td>
<td>r2c2</td>
<td>r2c3</td>
<td>r2c4</td>
</tr>
</tbody>
</table>

Unable to print table grid using jQuery

I am unable to print a grid. This is what I am trying to do:
Take the grid size as an input from the user.
Dynamically create the grid based on the input.
Below is a part of the code.
$(document).ready(function() {
$("#grid-input").click(function() {
$(".drawing-area").empty();
var rows = $("#row").val();
var cols = $("#col").val();
if (rows > 0 && cols > 0) {
for (var i = 1; i <= rows; i++) {
var rowClassName = 'row' + i;
$('<tr></tr>').addClass(rowClassName).appendTo('.drawing-area'); //Adding dynamic class names whenever a new table row is created
for (var j = 1; j <= cols; j++) {
var colClassName = 'col' + j;
$('<td width="20px" height="20px" style="border: 1px solid #000"></td>').addClass(colClassName).appendTo('.rowClassName');
}
}
} else {
alert("You haven't provided the grid size!");
}
});
});
});
<table class="drawing-area">
</table>
There is an error in your code, Last brackets are not required.
Append dom at the end of your code,
Try following code
$(document).ready(function() {
$("#grid-input").click(function() {
$(".drawing-area").empty();
var rows = $("#row").val();
var cols = $("#col").val();
if (rows > 0 && cols > 0) {
for (var i = 1; i <= rows; i++) {
var rowClassName = 'row' + i;
var tr = $('<tr>').addClass(rowClassName);
tr.appendTo('.drawing-area'); //Adding dynamic class names whenever a new table row is created
for (var j = 1; j <= cols; j++) {
var colClassName = 'col' + j;
$('<td width="20px" height="20px" style="border: 1px solid #000">').addClass(colClassName).appendTo(tr);
}
}
} else {
alert("You haven't provided the grid size!");
}
});
});
You can try to save the dynamic table row to a variable $tr first and then add the dynamic table column to that $tr variable like:
$("#grid-input").click(function() {
$(".drawing-area").empty();
var rows = $("#row").val();
var cols = $("#col").val();
if (rows > 0 && cols > 0) {
for (var i = 1; i <= rows; i++) {
var rowClassName = 'row' + i;
// Saving dynamic table row variable
var $tr = $('<tr/>').addClass(rowClassName).appendTo('.drawing-area');
for (var j = 1; j <= cols; j++) {
var colClassName = 'col' + j;
$('<td>'+ (i * j) +'</td>').addClass(colClassName)
// Append the new td to this $tr
.appendTo($tr);
}
}
} else {
alert("You haven't provided the grid size!");
}
});
.drawing-area{font-family:"Trebuchet MS",Arial,Helvetica,sans-serif;border-collapse:collapse;width:100%}
.drawing-area td,.drawing-area th{border:1px solid #ddd;padding:8px}
.drawing-area tr:nth-child(even){background-color:#f2f2f2}
.drawing-area tr:hover{background-color:#ddd}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Row: <input type="number" id="row"><br/>
Col: <input type="number" id="col"><br/>
<button id="grid-input">Save</button><br/><br/>
<table class="drawing-area">
</table>

Create element href in a table tag

I'm making a app in Javascript and html.
When you click on the button "find contact" , Then you see all the contacts from you're phone in the app. Then when you click on a name you can call that person.
This last thing have I done with a href, but I want my contacts below each other. Now they stands next to each other. Also this must into a table.
This is my code so far :
Javascript :
function findContact() {
var options = new ContactFindOptions();
options.filter = "";
options.multiple = true;
fields = ["displayName", "phoneNumbers"];
navigator.contacts.find(fields, contactfindSuccess, contactfindError, options);
function contactfindSuccess(contacts) {
for (var i = 0; i < contacts.length; i++) {
for (var j = 0; j < contacts[i].phoneNumbers.length; j++) {
var nummer = contacts[i].phoneNumbers[j].value;
var jens = contacts[i].displayName;
var para = document.createElement("a");
var t = document.createTextNode(jens);
para.appendChild(t);
para.title = jens;
para.href = "tel:" + nummer;
document.getElementById("abc").appendChild(para);
}
}
}
function contactfindError(message) {
alert('Failed because: ' + message);
}
}
HTML :
<table id="myDIV">
<tr class="header">
<th>Naam</th>
</tr>
<tr>
<td id="abc"></td>
</tr>
</table>
Javascript search function :
<script>
function myFunction() {
var input, filter, table, tr, td, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myDIV");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
</script>
EDIT --> Note that the search function will work only after the find contacts button is pressed. I'm assuming thats what you want. Cheers
Hi i'm assuming that you want to put all the contacts into one td. All you have to do is style the a tags to appear one below the other. check out the code below. If this is not what you had in mind let me know.
Also, I've taken a sample json object to display the data where there are people person1 and person2 with 2 and 3 phone numbers each.
var contacts = [];
var obj={
displayName:'abigail',
phoneNumbers:[{value:'xxxxxx'},{value:'yyyyyy'},{value:'zzzzz'}]
};
contacts.push(obj);
obj={
displayName:'ashley',
phoneNumbers:[{value:'xxxxxx'},{value:'yyyyyy'}]
};
contacts.push(obj);
obj={
displayName:'Markov',
phoneNumbers:[{value:'xxxxxx'},{value:'yyyyyy'}]
};
contacts.push(obj);
function contactfindSuccess() {
for (var i = 0; i < contacts.length; i++) {
for (var j = 0; j < contacts[i].phoneNumbers.length; j++) {
var nummer = contacts[i].phoneNumbers[j].value;
var jens = contacts[i].displayName;
var para = document.createElement("a");
var t = document.createTextNode(jens);
para.appendChild(t);
para.title = jens;
para.href = "tel:" + nummer;
document.getElementById("abc").appendChild(para);
}
}
}
function myFunction() {
var input, filter, table, tr, td, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
var td = document.getElementById("abc");
var a = td.getElementsByTagName("a");
for (i = 0; i < a.length; i++) {
if (a[i].innerHTML.substring(0, filter.length).toUpperCase()==filter) {
a[i].style.display = "";
} else {
a[i].style.display = "none";
}
}
}
#abc a{
float:left;
clear:left;
}
<input id="myInput" onkeyup="myFunction()" type="text"/>
<table id="myDIV">
<tr class="header">
<th>Naam</th>
</tr>
<tr>
<td id="abc"></td>
</tr>
</table>
<button onclick="contactfindSuccess()" style="margin-top:20px;">Find Contacts</button>

Calculate a new AveValue in TableCell while adding new Columns using JavaScript-not JQuery

I have a <th> header row with a stated class, and one fixed row with a stated class. Both are contenteditable. I'm adding new rows and new columns. I want to calculate the AverageValue in the final cell. I have tried the code on a fixed number of rows and it works, but when I try it this way it is only taking in the number of columns, not the DATA inserted. It is also not recognizing the row DATA. I'm clearly missing a function?!
I'm at the stage where I need an extra pair of eyes.
JavaScript:
func = function() {
var table = document.getElementById("mytable");
var rows = table.rows;
for (var j = 1; j < rows.length; j++) {
var total = 0;
var cells = rows[j].cells;
for (var i = 2; i < (cells.length - 1); i++) {
var a = document.getElementById("mytable").rows[j].cells[i].innerHTML;
a = parseInt(a);
if (!isNaN(a)) {
total = total + a;
}
}
total = total / (cells.length - 3);
total = Math.round(total);
if (total < 40) {
document.getElementById("mytable").rows[j].cells[cells.length - 1].style.backgroundColor = "red";
document.getElementById("mytable").rows[j].cells[cells.length - 1].style.color = "white";
}
document.getElementById("mytable").rows[j].cells[cells.length - 1].innerHTML = total + "%";
}
}
addRow = function() {
var table = document.getElementById('mytable'); // table reference
var row = table.insertRow(table.rows.length); // append table row
// insert table cells to the new row
for (i = 0; i < table.rows[0].cells.length; i++) {
createCell(row.insertCell(i), "-");
}
}
createCell = function(cell, text, style) {
var div = document.createElement('div');
txt = document.createTextNode(text);
div.appendChild(txt); // append text node to the DIV
div.setAttribute("class", style); // set DIV class attribute
div.setAttribute("className", style);
div.setAttribute("contenteditable", true);
div.setAttribute('placeholder', '' - '');
cell.appendChild(div); // append DIV to the table cell
}
createCellCol = function(cell, text, style) {
var div = document.createElement('div');
txt = document.createTextNode(text);
div.appendChild(txt); // append text node to the DIV
div.setAttribute("class", style); // set DIV class attribute
div.setAttribute("className", style);
div.setAttribute("contenteditable", true);
div.setAttribute("placeholder", "-");
cell.appendChild(div); // append DIV to the table cell
}
addColumn = function() {
var table = document.getElementById("mytable"); // table reference
var rowNums = table.rows.length;
for (i = 0; i < rowNums; i++) {
if (i == 0) {
createCell(table.rows[i].insertCell(table.rows[i].cells.length - 1), "-");
} else {
createCellCol(table.rows[i].insertCell(table.rows[i].cells.length - 1), "-");
}
}
}
HTML:
<table class="tg" id="mytable">
<tr>
<th class="tg-s6z2" contenteditable="true">Student Name</th>
<th class="tg-s6z2" contenteditable="true">Student ID</th>
<th class="tg-s6z2" contenteditable="true">Assignment 1</th>
<th class="tg-s6z2" contenteditable="true">Final Grade</th>
</tr>
<tr>
<td class="tg-031e" contenteditable="true">Student1</td>
<td class="tg-031e" contenteditable="true">StudentNo</td>
<td class="tg-0ord" contenteditable="true"></td>
<td class="tg-0ord" contenteditable="true"></td>
</tr>
</table>
<button id="btnFinalGrade" class="btn btn-action" onClick="func();">Final Grade</button>
<button id="btnaddRow" class="btn btn-action" onclick="addRow();">AddRow</button>
<button id="btnaddColumn" class="btn btn-action" onclick="addColumn();">AddColumn</button>
You were adding a div to td element which was throwing error while executing this line document.getElementById("mytable").rows[j].cells[i].innerHTML
which returns a div element not the text you entered!
No need to add a div, Here is the updated code,
func = function () {
var table = document.getElementById("mytable");
var rows = table.rows;
for (var j = 1; j < rows.length; j++) {
var total = 0;
var cells = rows[j].cells;
for (var i = 2; i < (cells.length - 1); i++) {
var a = document.getElementById("mytable").rows[j].cells[i].innerHTML;
a = parseInt(a);
if (!isNaN(a)) {
total = total + a;
}
}
total = total / (cells.length - 3);
total = Math.round(total);
if (total < 40) {
document.getElementById("mytable").rows[j].cells[cells.length - 1].style.backgroundColor = "red";
document.getElementById("mytable").rows[j].cells[cells.length - 1].style.color = "white";
}
document.getElementById("mytable").rows[j].cells[cells.length - 1].innerHTML = total + "%";
}
}
addRow = function () {
var table = document.getElementById('mytable'); // table reference
var row = table.insertRow(table.rows.length); // append table row
// insert table cells to the new row
for (i = 0; i < table.rows[0].cells.length; i++) {
createCell(row.insertCell(i), "-","tg-031e");
}
}
createCell = function (cell, text, style) {
var div = document.createElement('td');
txt = document.createTextNode(text);
cell.appendChild(txt); // append text node to the DIV
cell.setAttribute("class", style); // set DIV class attribute
cell.setAttribute("className", style);
cell.setAttribute("contenteditable", true);
cell.setAttribute('placeholder', '' - '');
//cell.appendChild(div); // append DIV to the table cell
}
createCellCol = function (cell, text, style) {
var div = document.createElement('td');
txt = document.createTextNode(text);
cell.appendChild(txt); // append text node to the DIV
cell.setAttribute("class", style); // set DIV class attribute
cell.setAttribute("className", style);
cell.setAttribute("contenteditable", true);
cell.setAttribute("placeholder", "-");
//cell.appendChild(div); // append DIV to the table cell
}
addColumn = function () {
var table = document.getElementById("mytable"); // table reference
var rowNums = table.rows.length;
for (i = 0; i < rowNums; i++) {
if (i == 0) {
createCell(table.rows[i].insertCell(table.rows[i].cells.length - 1), "-","tg-031e");
} else {
createCellCol(table.rows[i].insertCell(table.rows[i].cells.length - 1), "-","tg-s6z2");
}
}
}

JavaScript reading data into an array from a dynamic table of textfields

I'm dynamically creating a table using an HTML table and JavaScript Functions attatched to button clicks. I now want to take the data and store it into multidimensional array (if possible) using another button named finished. I'm having trouble even getting started with the last method to save it into array. I can't figure out how to retrieve the text data.
Here is my current HTML code.
<head>
<title>TableTest</title>
<script src="/javascript/func.js"></script>
</head>
<body>
<form>
<div id="Input">
<INPUT class="form-button" id="AddRow" type="button" value="Add Row" onclick="addRow('dataTable')" />
<INPUT class="form-button" id="DeleteRow" type="button" value="Delete Row(s)" onclick="deleteRow('dataTable')" />
<INPUT class="form-button" id="Finished" type="button" value="Finished" onclick="gatherData('dataTable')" />
<table id="dataTable" border="1" style="width:200px" id="mytable" align="center" cellspacing="3" cellpadding="4">
<th>Select</th>
<th>Text1</th>
<th>Text2</th>
<th>Text3</th>
<tr>
<td><INPUT type="checkbox" name="chk"/></td>
<td><INPUT type="text" name="text1"/></td>
<td><INPUT type="text" name="txt2"/></td>
<td><INPUT type="text" name="txt3"/></td>
</tr>
</table>
</div>
</form>
</body>
Here is my JavaScript file:
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
}
}
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
if(rowCount <= 2) {
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
}
function gatherData(){
//Tests
var table = document.getElementById('dataTable');
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
alert(rowCount);
alert(row);
alert(colCount);
}
I reworked TameBadger's answer to build the array by row instead of by column. I also added a check to see if the given cell has a value before referencing it. In my case, not all cells have values.
var table = document.getElementById('mainTable');
if (table === null)
return;
if (table.rows[0].cells.length <= 1)
return;
var tblData = [];
//Put a RowNumber name and values placeholder for the number of rows we have.
for (r = 0; r < table.rows.length; r++)
{
//Debug
//console.log(" row: ", r);
tblData.push({
name: "RowNumber" + r,
items: []
});
//Get the cells for this row.
var cells = table.rows[r].cells;
//Loop through each column for this row and push the value...
for (c = 0; c < cells.length; c++)
{
var inputElem = cells[c].children[0];
var tmpInputElem;
if (inputElem == null)
{
tmpInputElem = "";
}
else
{
tmpInputElem = inputElem.value
}
//Debug
//console.log(" row-cel: ", r, "-", c, " ", inputElem);
tblData[r].items.push(
{
//Comment out the type for now...
//inputType: inputElem.getAttribute('type'),
inputValue: tmpInputElem
});
}
}
//Debug
//printData(tblData);
I tried to keep it simple, and also jQuery clean, so to speak.
var data = [];
function gatherData() {
var table = document.getElementById('dataTable');
for (r = 1; r < table.rows.length; r++) {
var row = table.rows[r];
var cells = row.cells;
for (c = 0; c < cells.length; c++) {
var cell = cells[c];
var inputElem = cell.children[0];
var isInput = inputElem instanceof HTMLInputElement;
if (!isInput)
return;
var value = inputElem.value;
var isCheckbox = inputElem.getAttribute('type') == 'checkbox';
if (isCheckbox)
value = inputElem.checked;
var rowData = {};
rowData.inputType = inputElem.getAttribute('type');
rowData.inputValue = value;
data.push(rowData);
}
}
}
function startExec() {
gatherData();
for (i = 0; i < data.length; i++) {
console.log(data[i].inputType);
console.log(data[i].inputValue);
}
}
//just wait for the dom to load, and then execute the function for testing
document.addEventListener("DOMContentLoaded", startExec, false);
2nd Revision
function getData() {
var table = document.getElementById('dataTable');
if (table === null)
return;
if (table.rows[0].cells.length <= 1)
return;
var data = [];
for (l = 0; l < table.rows[0].cells.length; l++) {
data.push({
items: [],
name: "ColumnNumber" + l
});
}
for (i = 1; i < table.rows.length; i++) {
var cells = table.rows[i].cells;
for (c = 0; c < cells.length; c++) {
var inputElem = cells[c].children[0];
data[c].items.push({
inputType: inputElem.getAttribute('type'),
inputValue: inputElem.value
});
}
}
printData(data);
}
function printData(data) {
for (i = 0; i < data.length; i++) {
for (k = 0; k < data[i].items.length; k++) {
console.log(data[i].items[k].inputValue);
}
}
}
document.addEventListener("DOMContentLoaded", getData(), false);
It's great that you're starting off and doing the table manipulation yourself, and I would recommend continuing that, if you want to peak into a bigger codebase I would recommend checking out jTable's. Even though it's a jQuery plugin, you'll still be able to learn something from looking at the code structure for handling all the logic surrounding building a table according to a dataset and adding records etc.
Is this what you are looking for?
JSFIDDLE
$(document).ready(function(){
$('#Finished').click(function(){
var my_arr=[];
$('td').each(function(){
if ($(this).children().is(':checkbox') )
{
if($(this).children().prop('checked'))
{
my_arr.push($(this).children().val());
}
}else{
my_arr.push($(this).children().val());
}
})
console.log(my_arr);
})
})

Categories

Resources