Could anyone please tell me what is wrong with this code? I am trying to create a table from stratch and add ten rows and cells to it. Thanks in advance.
<!DOCTYPE html>
<html>
<head>
<title>Untitled</title>
<script type="text/javascript">
var cargar = function () {
var tabla = document.createElement("TABLE");
document.body.appendChild(tabla);
var cebreado = function () {
console.log("Inicio" + a);
for (var a = 0; a > 10; a++) {
tabla.appendChild(document.createElement("TR"));
console.log("Hola" + a);
for (var b = 0; b > 10; b++) {
tabla.appendChild(document.createElement("TD"));
}
}
}
;
return cebreado;
}
;
</script>
</head>
<body onload="cargar()">
</body>
</html>
You got a couple of things wrong:
You do not call the function cebreado, you simply refer to it
Both you for loops had > when it shold be <
You were not appending the TD into TR, but to the table itself.
Here is your code working:
<!DOCTYPE html>
<html>
<head>
<title>Untitled</title>
<script type="text/javascript">
var cargar = function () {
var tabla = document.createElement("TABLE");
document.body.appendChild(tabla);
var cebreado = function () {
console.log("Inicio" + a);
for (var a = 0; a < 10; a++) {
tabla.appendChild(document.createElement("TR"));
console.log("Hola" + a);
for (var b = 0; b < 10; b++) {
tabla.lastChild.appendChild(document.createElement("TD"));
}
}
}
;
return cebreado();
}
;
</script>
</head>
<body onload="cargar()">
</body>
</html>
try this : http://jsfiddle.net/mig1098/nt3sd8dw/
var cargar = function () {
var tabla = document.createElement("TABLE");
document.body.appendChild(tabla);
var cebreado = function () {
for (var a = 0; a < 10; a++) {
console.log("Inicio" + a);
var tr = document.createElement("TR");
tabla.appendChild(tr);
console.log("Hola" + a);
for (var b = 0; b < 10; b++) {
var td = (document.createElement("TD"));
tr.appendChild(td);
var text = document.createTextNode("Hello");
td.appendChild(text);
}
}
}
;
return cebreado();
}
;
cargar();
Miglio answered it already.
What you can do, too, is change onload="cargar()" to onload="cargar()()"
Example:
function cargar() {
function cebreado() {
alert("x");
}
return cebreado;
}
cargar()();
The final behaviour will be the same, but they are different things.
Related
My question is as follows, how could I pass images that are inside an array to a div?
I've multiplied the div#imagem and I need to pass the array images to it.
But I do not know how.. Can someone help me?!
My JavaScript/JQuery
var divBoard = $("<div id='board'></div>");
$("body").after(divBoard);
var titleGame = $("<h1></h1>").text("Memory Game");
var btnReset = $("<input id='btn-reset' type='button' onclick='reset()' value='Reset'>");
$("#board").append(titleGame);
$("#board").append(btnReset);
(function (){
var images = ['img/facebook.png','img/android.png','img/chrome.png','img/firefox.png','img/html5.png','img/googleplus.png','img/twitter.png','img/windows.png','img/cross.png'];
$(window).load(function () {
$('#board').html('');
var numCards = 16;
for (var i = 1; i <= numCards; i++) {
$("#board").append("<div class='image" + i + " images'></div>") &&
$(".image" + i).clone().appendTo("#board");
}
var cards = $(".images");
for (var i = 0; i < cards.length; i++) {
var target = Math.floor(Math.random() * cards.length - 1) + 1;
var target2 = Math.floor(Math.random() * cards.length - 1) + 1;
var target3 = Math.floor(Math.random() * cards.length - 1) + 1;
}
})();
app.start();
});
My HTML
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="style.css">
<title>JavaScript Memory Game</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script charset="utf8">
var app = { nrComponents:0 };
app.getComponent = function(name) {
if (!app[name]) {
app[name] = {};
app[app.nrComponents++] = name;
}
return app[name];
};
</script>
<script src="script.js" charset="utf8"></script>
</body>
</html>
Here are critical 2 problems I listed. Some line in your code seems not neccecery and hard to debug for it. I would suggest to simplify your code for better debugging.Hope it helps..
$("body").after(divTabuleiro); I think this will insert content after 'body' instead of putting 'divTabuleiro' inside the 'body'.
$("#tabuleiro").append(""); should have tag inside for insert images.
// Create a start function and move you initial code here....
app.start = function(){
var imagens = [
'https://images-na.ssl-images-amazon.com/images/G/01/img15/pet-products/small-tiles/23695_pets_vertical_store_dogs_small_tile_8._CB312176604_.jpg',
'http://www.pressunion.org/wp-content/uploads/2016/11/1-2.jpg',
'http://www.feixiubook.com/wp-content/uploads/2016/06/01-25.jpg'
];
var divTabuleiro = $("<div id='tabuleiro'></div>");
$("body").append(divTabuleiro);
var titulo = $("<h1></h1>").text("Jogo da Memória");
var btnReset = $("<input id='btn-reset' type='button' onclick='reset()' value='Reset'>");
$("#tabuleiro").append(titulo);
$("#tabuleiro").append(btnReset);
$('#tabuleiro').html('');
var numCards = 3;
for (var i = 0; i < numCards; i++) {
var img = imagens[i];
$("#tabuleiro").append("<div class='my-image-" + i + " my-image'><img src='" + img + "'></div>") && $(".my-image-" + i).clone().appendTo("#tabuleiro");
}
// randomize cards in stack
var cards = $(".my-image");
for (var i = 0; i < cards.length; i++) {
var target = Math.floor(Math.random() * cards.length - 1) + 1;
var target2 = Math.floor(Math.random() * cards.length - 1) + 1;
var target3 = Math.floor(Math.random() * cards.length - 1) + 1;
cards.eq(target).before(cards.eq(target2)).before(cards.eq(target3));
}
};
// Maybe create another function
app.reset = function(){
};
$(window).ready(function() {
// Because you have created a start function above. you can call it when document ready
app.start();
});
.my-image {
width: 200px;
height: 200px;
overflow: hidden;
float: left;
}
.my-image img {
height: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
// Create a namespace of app
var app = { nrComponents:0 };
// Add a function 'getComponent' in to it
app.getComponent = function(name) {
if (!app[name]) {
app[name] = {};
app[app.nrComponents++] = name;
}
return app[name];
};
// So There is no start() function inside......
// we can add start function later..
</script>
Hm.. I somehow don't understand your exact request, but for making images based on an array you can use this as a guide :
var imagens = ['img/facebook.png','img/android.png','img/chrome.png','img/firefox.png','img/html5.png','img/googleplus.png','img/twitter.png','img/windows.png','img/cross.png'];
$.each(imagens,function(index,imageSrc){
$("Parent Element").append('<img src="'+imageSrc+'" />');
});
hope it helps.
Actually I'm trying to count the number of User Stories and its associated QA Task (TaskType) for each projects based upon Release and Iteration filter. I'm able to achieve it using SDK 1.32., but Release and Iteration dropdown are not working properly in IE browser.
also please let me know whether it's advisable to upgrade current SDK version to 2.0 or is there any workaround to resolve it.
Thanks in advance
Script :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta name="Name" content="Project Board" />
<script type="text/javascript" src="/apps/1.32/sdk.js">
</script>
<script type="text/javascript">
function ReleaseDependencies() {
var rallyDataSource;
var cardBoard;
var releaseDropdown;
var table;
var header;
var task_count = 0;
var data = new Array();
var taskData = new Array();
var iterDropdown;
function buildHeaders() {
var tableConfig = {
sortingEnabled: false,
columnKeys: [
'module', 'totstories', 'totcompleted', 'totinprogress',
'totqa', 'totblocked'
],
columnHeaders: [
'MODULE', 'STORIES', 'COMPLETED', 'IN-PROGRESS', 'QA TASKS', 'BLOCKED'
],
columnWidths: ['16%', '16%', '16%', '16%', '16%', '16%']
};
table = new rally.sdk.ui.Table(tableConfig);
}
function destroyTables() {
if (table) {
table.destroy();
}
}
function onReleaseSelected(releases, eventArgs) {
if (iterDropdown) {
iterDropdown.destroy();
destroyTables();
}
var queryConfig = {
label: "Select Iteration "
};
iterDropdown = new rally.sdk.ui.IterationDropdown(queryConfig, rallyDataSource);
iterDropdown.display(document.getElementById("releaseDiv2"), onIterationSelected);
releaseDropdown.addEventListener("onChange", display);
}
function onIterationSelected(releases, eventArgs) {
if (table) {
table.destroy();
}
var queryConfig = {};
findProjects();
iterDropdown.addEventListener("onLoad", findProjects);
iterDropdown.addEventListener("onChange", findProjects);
}
this.display = function() {
destroyTables();
rallyDataSource = new rally.sdk.data.RallyDataSource('1283334',
'2013244650',
'false',
'true');
rally.sdk.ui.AppHeader.showPageTools(true);
releaseDropdown = new rally.sdk.ui.ReleaseDropdown({}, rallyDataSource);
releaseDropdown.display(document.getElementById("releaseDiv"), onReleaseSelected);
};
function findProjects() {
buildHeaders();
var targetReleaseName = releaseDropdown.getSelectedName();
var relCond = '(Release.Name = "_REL_TARGET_")'.replace('_REL_TARGET_', targetReleaseName);
var targetIterationName = iterDropdown.getSelectedName();
var iterCond = '(Iteration.Name = "_ITER_TARGET_")'.replace('_ITER_TARGET_', targetIterationName);
var storyCriteria = '(' + relCond + ' AND ' + iterCond + ')';
rallyDataSource.find({
key: "stories",
type: "hierarchicalrequirement",
query: storyCriteria,
fetch: 'FormattedID,Name,Project,Parent,ScheduleState,Tasks,TaskType'
}, onProjectsRetrieved);
}
function onProjectsRetrieved(results) {
var rowCount = 0;
var proCount = 0;
var proName;
var stateCount = 0;
var progCount = 0;
var n;
var fields;
var fieldLength = 0;
var queryConfigs;
var task_count = 0;
var blocked = 0;
for (var j = 0; j < results.stories.length; j++) {
var abc = results.stories[j].Project.Name;
data.push(abc);
data.sort();
}
data = unique(data);
for (var i = 0; i < data.length; i++) {
table.setCell(rowCount, 'module', data[i]);
var pr = data[i];
rally.forEach(results.stories, function(proj) {
story = proj;
if (proj.Project.Name == pr) {
proCount++;
n = n + proj.Name + "~";
fields = n.split('~');
fieldLength = fields.length - 1;
proName = proj.Project.Name
if (proj.ScheduleState == "Completed") {
stateCount++;
} else if (proj.ScheduleState == "In-Progress") {
progCount++;
}
if (proj.blocked == true) {
blocked++;
}
for (var q = 0; q < story.Tasks.length; q++) {
if (story.Tasks.length > 0) { //if(pr == story.Tasks[q].Project.Name)
if (story.Tasks[q].TaskType == "QA") {
task_count++;
break;
}
}
}
}
});
table.setCell(rowCount, 'totstories', fieldLength);
table.setCell(rowCount, 'totcompleted', stateCount);
table.setCell(rowCount, 'totinprogress', progCount);
table.setCell(rowCount, 'totqa', task_count);
table.setCell(rowCount, 'totblocked', blocked);
rowCount++;
proCount = 0;
stateCount = 0;
progCount = 0;
fieldLength = 0;
task_count = 0;
n = null;
if (blocked > 0) {
blocked = 0;
}
}
table.display(document.getElementById('projects'));
}
var unique = function(origArr) {
var newArr = [],
origLen = origArr.length,
found,
x, y;
for (x = 0; x < origLen; x++) {
found = undefined;
for (y = 0; y < newArr.length; y++) {
if (origArr[x] === newArr[y]) {
found = true;
break;
}
}
if (!found) newArr.push(origArr[x]);
}
return newArr;
}
} //rally.addOnLoad(onLoad);
</script>
<style type="text/css">
#header {
margin-bottom: -22px;
}
</style>
<script type="text/javascript">
function onLoad() {
var releaseDependencies = new ReleaseDependencies();
releaseDependencies.display();
}
rally.addOnLoad(onLoad);
</script>
</head>
<body>
<div id="releaseDiv">
</div>
<div id="releaseDiv2">
</div>
<br/>
<br/>
<div id="projects">
</div>
</body>
</html>
App SDK 1 is based on dojo 1.6, which officially supported IE 6, 7 and 8. App SDK 1 has been deprecated for some time in favor of App SDK 2.0. If you can upgrade that would be the ideal solution. Otherwise, if you can give some more insight into what exactly is not working correctly and what specific IE version you're having trouble with maybe a workaround can be found.
this code for javascript not working.can any one help me with this.i've tried a lot but couldn't find out what's wrong here!!checked every line .i dont know if the code is wrong or there is any problem with my browser
<html>
<head>
<title>table dynamic</title>
<style>
tr{width:100%;height:100%;border:1px solid black;}
td{height:33%;width:33%;padding:10px;}
.tableShape{
width:300px;
height:300px;
font-size:30px;
text-align:centre;
color:red;
}
table{border:1px solid black;padding:10px;}
</style>
</head>
<body>
<script>
var i, j;
var arr = new Array(3);
for (i = 0; i < 3; i++) {
arr[i] = new Array(3);
}
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
arr[i][j] = 1;
}
}
function tabs() {
var k, t;
var m = document.createElement("table");
m.setAttribute('class', "tableShape");
for (k = 0; k < 3; k++) {
var p = m.insertRow(k);
for (t = 0; t < 3; t++) {
var s = p.insertCell(t);
s.innerHTML += arr[i][j];
}
}
}
window.onLoad = tabs();
</script>
</body>
</html>
You have to append your created element to the DOM:
function tabs() {
var k, t;
var m = document.createElement("table");
m.setAttribute('class', "tableShape");
for (k = 0; k < 3; k++) {
var p = m.insertRow(k);
for (t = 0; t < 3; t++) {
var s = p.insertCell(t);
s.innerHTML += arr[i][j];
}
}
document.body.appendChild(m);
}
When you create DOM elements in javascript, they are created in memory detached from DOM, to see them you have to append it to some node in DOM.
document.body.appendChild(m);
You are doing a nested operation using variables k and t so use it inside the loop
s.innerHTML+=arr[k][t];
Here is a fiddle http://jsfiddle.net/AmH22/1/
This is the table created dynamically using javascript, I want to show this textbox value in alert message using GetCellValues() function.
function makeTable()
{
row=new Array();
cell=new Array();
row_num=20;
cell_num=4;
tab=document.createElement('table');
tab.setAttribute('id','newtable');
tbo=document.createElement('tbody');
tbo.setAttribute('id','tabody');
for(c = 0;c < row_num; c++)
{
row[c]=document.createElement('tr');
for(k = 0; k < cell_num; k++)
{
cell[k] = document.createElement('td');
if (k > 0)
{
cont=document.createElement("input");
cont.setAttribute('type','text');
cell[k].appendChild(cont);
row[c].appendChild(cell[k]);
}
else
{
cont=document.createTextNode("0" + (c+1));
cell[k].appendChild(cont);
row[c].appendChild(cell[k]);
}
}
tbo.appendChild(row[c]);
}
tab.appendChild(tbo);
document.getElementById('mytable').appendChild(tab);
mytable.setAttribute("align", "top-left");
}
Please check the GetCellValues() function, this function is not showing the textbox value in alert message.
function GetCellValues()
{
row=new Array();
cell=new Array();
row_num=20;
cell_num=4;
tab = document.getElementsByTagName('table');
tbo = tab.getElementsByTagName('tbody');
for(c = 0;c < row_num; c++)
{
row = tbo.getElementsByTagName('tr');
for(k = 0; k < cell_num; k++)
{
cell = row.getElementsByTagName('td');
{
cont=cell.getElementsByTagName('input');
{
alert(cont.value);
}
}
}
}
}
I think you need some modification in GetCellvalues function as tab.getElementsByTagName('tbody'); will not get elements having tag name tbody for thi you should use document.getElementsByTagName.
you can check working demo of you code here
If you are getting an alert box with [object HTMLCollection] message in it, then you need to use
alert(cont[0].value) in place of alert(cont.value) at the end of your GetCellValues function.
getElementsByTagName returns collection, you need to iterate through it or assume the first element - apply to row, cell, e.g.
var rows = tbo.getElementsByTagName('tr');
for (var c = 0; c < row_num; c++) {
row = rows[c];
var cells = row.getElementsByTagName('td');
for (var k = 0; k < cell_num; k++) {
cell = cells[k];
// and so on
}
}
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<table id="mytable"></table>
<input type="button" onclick="GetCellValues(20, 4);" value="click me" />
<script type="text/javascript">
function makeTable() {
row = new Array();
cell = new Array();
row_num = 20;
cell_num = 4;
tab = document.createElement('table');
tab.setAttribute('id', 'newtable');
tbo = document.createElement('tbody');
tbo.setAttribute('id', 'tabody');
for (c = 0; c < row_num; c++) {
row[c] = document.createElement('tr');
for (k = 0; k < cell_num; k++) {
cell[k] = document.createElement('td');
if (k > 0) {
cont = document.createElement("input");
cont.setAttribute('type', 'text');
cont.setAttribute('value', '');
cell[k].appendChild(cont);
row[c].appendChild(cell[k]);
}
else {
cont = document.createTextNode("0" + (c + 1));
cell[k].appendChild(cont);
row[c].appendChild(cell[k]);
}
}
tbo.appendChild(row[c]);
}
tab.appendChild(tbo);
document.getElementById('mytable').appendChild(tab);
mytable.setAttribute("align", "top-left");
}
makeTable();
function GetCellValues(row_num, cell_num) {
var arrInput = document.getElementsByTagName('input');
var index = (row_num - 1) * (cell_num - 1);
alert(arrInput[index].value);
}
</script>
</body>
</html>
A shortcut approach would be to use ID attribute of tag.
Sample TD tag with ID:
<td id="1_1">1st row 1st column</td><td id="1_2">1st row 2nd column</td>
Javascript to get TD with ID:
var row_len=1,col_len=2;
for (r = 0; r< row_len; r++) {
for (c = 0; c < coll_len; c++) {
alert(document.getElementById(r+'_'+c));
}
}
<html>
<head>
<title>Array of Arrays</title>
<script type="text/javascript">
function matrix()
{
var e=prompt("Cols?",0);
var f=prompt("Rows?",0);
var matrix = new Array();
for (var i=0;i<e;i++)
{
matrix[i] = new Array();
for (var j=0;j<f;j++)
{
matrix[i][j]=Math.floor((Math.random()*1000)+1);
}
}
for (var i=0; i<=e-1; i++)
{
document.getElementById("keret").innerHTML=
document.getElementById("keret").innerHTML+"<tr>";
for (var j=0; j<=f-1; j++)
{
document.getElementById("keret").innerHTML=
document.getElementById("keret").innerHTML+"<td>"+matrix[i][j]+"</td>";
}
document.getElementById("keret").innerHTML=
document.getElementById("keret").innerHTML+"</tr>";
}
document.getElementById("keret").innerHTML=
document.getElementById("keret").innerHTML+"</table>";
}
</script>
</head>
<body onload="matrix()">
<table border="1" id="keret">
</body>
</html>
This script makes a user defined array of arrays, and filling it up with random numbers. My problem is:
I can't make the script to put the values in dividual cells.
Your second loop can be as follows:
for (var i = 0; i < e; i++) {
var row = document.createElement("tr");
for (var j = 0; j < f; j++) {
var cell = document.createElement("td");
cell.innerHTML = matrix[i][j];
row.appendChild(cell);
}
document.getElementById("keret").appendChild(row);
}
This appends a tr element for each row and a td element for each column within the row. Then it appends the row to your table. Your HTML would be slightly modified as well:
<table border="1" id="keret"></table>
(Rows & Columns prompts need to be switched but I didn't want to mess up your variable names).
Fiddle: http://jsfiddle.net/verashn/7Rwnc/
<html>
<head>
<title>Array of Arrays</title>
<script type="text/javascript">
function matrix() {
var e = prompt("Cols?",0),
f = prompt("Rows?",0),
allRows = [],
row = [];
for (var i = 0; i < e; i += 1) {
row = ['<tr>', '</tr>']; // this serves as your initial template
for (var j = 0; j < f; j += 1) {
// now create the columns
row.splice(-1, 0, '<td>' + Math.floor((Math.random()*1000)+1) + '</td>')
}
allRows.push(row.join(''));
}
document.getElementById("keret").innerHTML = allRows.join('');
}
</script>
</head>
<body onload="matrix()">
<table border="1" id="keret"></table>
</body>
</html>