Can someone please tell me what I'm doing wrong?
I think it's something with the string adding;
I've also tried:
var column = $("<td></td>")
instead of:
var column = $("<td>")
etc
and it's always the same result on the HTML : "[object Object]"
What am I doing wrong?
$(function() {
createTable(8);
});
function createTableColumn() {
var column = $("<td>");
return column;
}
function createTableRow(gameBoardSize) {
var columns = "";
var row;
for(counter = 0; counter < gameBoardSize; counter++) {
columns = columns + createTableColumn();
}
row = $("<tr>").append(columns);
return row;
}
function createTable(gameBoardSize) {
var rows = "";
for(counter = 0; counter < gameBoardSize; counter++) {
rows += createTableRow(gameBoardSize);
}
$("#gameboard-table").append(rows);
}
You are accidentally performing a string concatenation operation with += createTableRow.... Change rows to an array and use push instead
var rows = [];
for(counter = 0; counter < gameBoardSize; counter++) {
rows.push(createTableRow(gameBoardSize));
}
+ is for concatenating strings, not jQuery objects.
Just append directly to the jQuery objects:
function createTableRow(gameBoardSize) {
var row = $("<tr>");
for(var counter = 0; counter < gameBoardSize; counter++) {
row.append(createTableColumn());
}
return row;
}
function createTable(gameBoardSize) {
for(var counter = 0; counter < gameBoardSize; counter++) {
$("#gameboard-table").append(createTableRow(gameBoardSize));
}
}
Make sure you use local variables for loop counters. Otherwise, the for loop in createTableRow updates the counter in createTable, which causes that loop to end prematurely.
$(function(){
createTable(8);
var i=0;
$('td').each(function(){
i++;
$(this).text(i);
});
});
function createTable(number){
for(var count = 0;count<number;count++){
$('#gameboard-table').append('<tr>');
$('tr').append('<td>');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<table id="gameboard-table"></table>
just string concatenation and one append.
function createTable(rowsCount, columnsCount) {
var rows = "";
var cell = "";
var table = $("<table />")
for (var i = 0; i < columnsCount; i++) {
cell += "<td></td>";
}
for (var i = 0; i < rowsCount; i++) {
rows += "<tr>" + cell + "</tr>";
}
table.append(rows);
return table;
}
Related
I am not getting the grid cell value.It's always empty. How can i get the cellvalue?
Code:
function VallidRcvQuantity (txtcurrentrcved) {
var grid = document.getElementById("<%=gvGoodReceived.ClientID%>");
var txtcurrentrcvamount = txtcurrentrcved;
for (var i = 0; i < grid.rows.length - 1; i++) {
var cellValue = $("#gvGoodReceived").find("tr:eq(" + i + ")").find("td:eq(2)").text();
if (Number(txtcurrentrcvamount) > Number(cellValue)) {
alert("Receive quantity must be less or equal PO quantity");
return false;
}
}
return true;
}
The reason you are not getting a cell value is because for the row with index 0, there are no td elements but only th elements within a tr element. This row is the header row.
So, you must either skip the first row in your original code or use code like below.
function getGridViewCellValue() {
var grid = document.getElementById("<%=gvGoodReceived.ClientID%>");
for (var i = 0; i < grid.rows.length - 1; i++) {
var cell = $("#<%=gvGoodReceived.ClientID%>").find("tr:eq(" + i + ")").find("td:eq(2)");
if (cell.length > 0) {
var cellValue = cell.text();
return cellValue;
}
}
return null;//means no cell value was found
}
I'm doing a function that creates a table in JS.
I create a variable table_row fill it and then add table_layout.appendChild(table_row); it to the table_layout element.
Next, I clean it table_row through innerHTML='', but when cleaning, the variable that I ALREADY added to the element table_layout is also cleared.
Why is this happening?
Should the added element be cleared?
How can this be avoided?
Look at the CODE.
var columns = ["col1", "col2", "col3"];
var rows = 5;
function Table() {
var table_layout = document.createElement("table");
var table_row = document.createElement("tr");
for (var i = 0; i < columns.length; i++) {
// main row
table_row.innerHTML += "<th>" + columns[i] + "</th>";
}
table_layout.appendChild(table_row); //add in table element
// table_row.innerHTML = ""; //If you uncomment this line, then we get an empty output!
//refresh table_row html, that would generate a new line
//But when cleaning. Cleared in the previously added item in table_layout .... how??
// for (var j = 0; i < columns.length; j++) {
// table_main_row.innerHTML += '<td></td>';
// }
// for (var i = 0; i < rows; i++) {
// table_layout.appendChild(table_row);
// }
return table_layout;
}
var div = document.getElementById("qqq");
div.appendChild(Table());
#qqq {
background: red;
}
<div id="qqq"></div>
The table_row variable contains a reference. You will need to create a new element for each row.
// creates a DOM Element and saves a reference to it in the table_row variable
var table_row = document.createElement("tr");
// updates the DOM Element through the reference in the table_row variable
table_row.innerHTML += "<th>" + columns[i] + "</th>";
// still references the DOM Element, so you are clearing its content
// table_row.innerHTML = "";
You will need to . . .
// create a new DOM Element to use
table_row = document.createElement("tr");
// then update its contents
table_main_row.innerHTML += '<td></td>';
. . . for each iteration.
See JavaScript on MDN for tutorials, references, and more.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" language="javascript">
var columns = ["col1", "col2", "col3"];
var rows = 5;
function createNewRow(headerRow)
{
var newRowElem = null;
try
{
newRowElem = document.createElement("tr");
for (var i = 0; i < columns.length; i++)
{
if(headerRow) newRowElem.innerHTML += "<th>" + columns[i] + "</th>";
else newRowElem.innerHTML += "<td>" + columns[i] + "</td>";
}
}
catch(e)
{
alert("createNewRow Error" + e.Message);
}
finally
{
}
return newRowElem;
}
function Table()
{
var table_layout = null;
try
{
table_layout = document.createElement("table");
// Create Header Row
table_layout.appendChild(createNewRow(true));
// Create Other Rows
for (var i = 0; i < rows; i++)
{
table_layout.appendChild(createNewRow(false));
}
}
catch(e)
{
alert("Table Error: " + e.Message);
}
finally
{
}
return table_layout;
}
</script>
<style>
#qqq {
background: red;
}
</style>
</head>
<body>
<div id="qqq"></div>
<script type="text/javascript" language="javascript">
var div = document.getElementById("qqq");
div.appendChild(Table());
</script>
</body>
</html>
I did so.
var table_layout = document.createElement('table');
table_layout.setAttribute('id', 'main_table');
table_layout.setAttribute('border', '1');
var row = document.createElement('tr');
row.setAttribute('class', 'main_row');
for (var i = 0; i < this.fields.length; i++) { // строка с именами столбцов
var th = document.createElement('th');
th.setAttribute('class', 'cell_name');
th.innerHTML = this.fields[i];
row.appendChild(th);
}
table_layout.appendChild(row); //добавляем
row = document.createElement('tr'); // очищаем от старых элементов строку (переопределяем)
row.setAttribute('class', 'table_row');
var td = document.createElement('td');
td.setAttribute('class', 'table_cell');
// td.setAttribute('ondblclick', 'input_func()');
td.addEventListener('click', function () {
alert();
});
td.innerHTML='000';
for (var j = 0; j < this.fields.length; j++) { // создаем строку с N-количеством ячеек
row.appendChild(td.cloneNode(true));
}
for (var i = 0; i < this.rows; i++) { // Добавляем её есколько раз через клона
table_layout.appendChild(row.cloneNode(true));
}
But then redistribution with functions for the table.
var table_layout = document.createElement('table');
table_layout.setAttribute('id', 'main_table');
table_layout.setAttribute('border', '1');
var row = table_layout.insertRow(0);
var cell;
for (var j = 0; j < this.fields.length; j++) {
cell = row.insertCell(j);
cell.outerHTML = '<th>' + this.fields[j] + '</th>';
cell.className = 'cell_name';
}
for (var i = 0; i < this.rows; i++) {
row = table_layout.insertRow(i + 1);
row.className = 'row_table';
for (var n = 0; n < this.fields.length; n++) {
cell = row.insertCell(n);
// cell.innerHTML = '00';
cell.className = 'table_cell';
cell.innerHTML = ' ';
}
}
return table_layout;
I need to return a total IR for each table cell. This is not working And I am not sure why. How
$scope.getTotalb = function () {
var totalb = 0;
for (var i = 0; i < $scope.items.length; i++) {
if (120 > $scope.items[i].product && $scope.items[i].product> 90) {
var product = $scope.items[i].IR;
totalb += ($scope.items[i].IR);
}
return totalb;
}
}
$scope.getTotalc = function () {
var totalc = 0;
for (var i = 0; i < $scope.items.length; i++) {
if (90 > $scope.items[i].product&& $scope.items[i].product> 60) {
var product = $scope.items[i].IR;
totalc += ($scope.items[i].IR);
}
return totalc;
}
}
For Each table data cell, call the function to get total.
<td><b>Total:</b></td>
<td><b>{{Totala()}}</b></td>
<td><b></b>{{Totalb()}}</td>
There are multiple errors in your code.
First, you should put the return statement at the end of your function instead of within your for loop.
Second, the names of the functions are different in your template. In your controller you use getTotalb but in the template you use Totalb.
You should put your return statement outside of for loop
remove the "return ...." from your 2 "for" loops and make your totals available through the scope.
$scope.getTotalb = function () {
var totalb = 0;
for (var i = 0; i < $scope.items.length; i++) {
if (120 > $scope.items[i].product && $scope.items[i].product> 90) {
var product = $scope.items[i].IR;
totalb += ($scope.items[i].IR);
}
}
$scope.totalb=totalb ;
}
$scope.getTotalc = function () {
var totalc = 0;
for (var i = 0; i < $scope.items.length; i++) {
if (90 > $scope.items[i].product&& $scope.items[i].product> 60) {
var product = $scope.items[i].IR;
totalc += ($scope.items[i].IR);
}
}
$scope.totalc=totalc ;
}
I have a unique problem that I hope someone can help with. I have a page that pulls data from a controller with AJAX and presents it to this function to construct a table:
// make rows in table from json data
function makeTableRows() {
if (jsonTableData != null) {
tbl = null;
tbl = createTable('tableResults');
// constructHeader(tbl, 'left', jsonTableData[0]);
newHeader(tbl, 'left', jsonTableData[0]);
var totalItems = jsonTableData.length;
var topItem;
topItem = 0;
if ((lastItem + perpage) > totalItems) {
topItem = totalItems;
$(".btnNext").prop('disabled', true);
}
else {
topItem = lastItem + perpage;
}
for (var i = lastItem; i <= topItem - 1; i++) {
makeTableRow(tbl, jsonTableData[i], 'left', true, 'showTourDetails(' + jsonTableData[i]["TransactionID"] + ',' + i + ')', 0);
}
$("#divSearchResults").html(tbl);
makePagesLabel();
makeTableFooter(tbl);
}
}
the function inside the separate file is this:
function constructHeader(table, alignment, firstRow) {
if (firstRow != null) {
var thead = document.createElement('thead');
table.appendChild(thead);
var tr = document.createElement('tr');
for (var key in firstRow) {
var header = key.match(/[A-Z][a-z]*/g);
var newHeader = '';
for (var i = 0; i <= header.length - 1; i++) {
newHeader += header[i] + ' ';
}
var th = document.createElement('th');
var text = document.createTextNode(newHeader);
th.appendChild(text);
th.style.textAlign = alignment;
th.style.cursor = 'pointer';
th.setAttribute('title', "Sort by " + newHeader);
th.onclick = function () {
var rows = $(table).find('tbody').find('tr').toArray().sort(comparer($(this).index()));
this.asc = !this.asc;
if (!this.asc) {
rows = rows.reverse();
}
for (var j = 0; j < rows.length; j++) {
$(table).append(rows[j]);
}
$(table).find('tbody').find('tr:even').css("background-color", "#dae5f4");
$(table).find('tbody').find('tr:odd').css("background-color", "#b8d1f3");
};
tr.appendChild(th);
}
thead.appendChild(tr);
}
}
Basically the function creates a sort process for the header of each column. After the sort of the column, I want to reapply the zebra striping that is applied with the class of the table. If I don't try to reapply I end up with the striping all messed up. Now, the problem is that if I copy the function into the .cshtml page and give it the name of 'newheader', the re-striping works fine. It does not work in the separate JS file and I cannot figure out why. Anyone have any clues?
I can't separate row and column td's as I create a 2d table with jquery..
How do I create 10 rows 10 columns 2d table:
what I have done so far:
$(document).ready(function () {
for (var i = 1; i <= 10; i++) {
$('.box').append('<td/>' + '</p>');
for (var j = 1; j <= 10; j++); {
$('.box').append('<td/>');
}
}
});
http://jsfiddle.net/VS37n/
thnx in advance!
You want a table that has 10 columns and 10 rows.
var rows = 10;
var cols = 10;
In an HTML table structure, rows come first in the hierarchy, so, create those first:
$(document).ready(function() {
var rows = 10;
var cols = 10;
var box = $('.box');
for (var r = 0; r < rows; r++) {
var tr = $('<tr>');
//Here we will append the columns to the row before appending it to the box.
box.append(tr);
}
});
The above code only makes 10 rows for us. Now we need to add 10 columns to each row:
$(document).ready(function() {
var rows = 10;
var cols = 10;
var box = $('.box');
for (var r = 0; r < rows; r++) {
var tr = $('<tr>');
for (var c = 0; c < cols; c++) {
tr.append($('<td><p></p></td>')); //Create the table cell, with a p element as in your example, and append it to the row.
}
box.append(tr);
}
});
See this FIDDLE
UPDATE
I just noticed that the jQuery selector from your post selects the <div> element with class .box. You want to add these rows and columns, however, to a <table> element, which doesn't exist. I'd suggest you add a <table> element into your HTML, or, add it with Javascript before adding the rows.
If you can add a <table> element inside of your .box div, then you would just change the following line:
var box = $('.box');
to:
var box = $('.box table:first');
If you can't change the HTML for some reason, then you can dynamically create the table before the rows and columns:
var box = $('<table>').appendTo('.box');
Is this what you're trying to do?
$(document).ready(function () {
var tdHtml = "":
var trHtml = "";
var tableHtml = "";
for(var i=1;i<=10;i++)
{
tdHtml += "<td></td>";
}
for(var j=1;j<=10;j++);
{
trHtml += ("<tr>" + tdHtml + "</tr>");
}
tableHtml = ("<table>" + trHtml + "</table>");
$('.box').innerHtml(tableHtml);
});
You had a ; after your for loop :
for (var j = 1; j <= 10; j++); {
$('.box').append('<td/>');
}
Furthermore, you are not adding <tr> elements.
See the updated fiddle