Generate Html table using for loop - javascript

Please help with below mentioned scenario->
I am having wanna display values from 1 to 30 in a table such a way that nos 1,2,3 should come in one tag and like wise 4,5,6 in other tr tag ans so on till 30 value. I wanna use table for displaying values in a element of a table. wherein each value like "1" should display in one , no "2" should display in different <TD> and so on.
I mean to say that value "1" should be displayed in single <TD> of <Table> tag ,value "2" should be displayed in another <td> tag and so on ,Also after three subsequent <TD>s one <Tr> should be used. Output should be as folllows ->
1 2 3
4 5 6
7 8 9
and so on!
Early response would be much appreciated. Thanks.
I have tried Code as given below,
<script type="text/javascript">
document.write(" <table width='673' align='center' cellpadding='2' cellspacing='1'>");
document.write(" <tr>");
document.write(" <td valign = 'top'>");
document.write(" </td>");
document.write(" </tr>");
var cnt = 0;
for (var idx = 1; idx <= 30; idx++)
{
cnt = cnt + 1;
document.write(" <tr>");
document.write(" <td valign = 'top'>");
document.write(" <table width='100px' align='center' cellpadding='2' cellspacing='1'>");
document.write(" <tr>");
document.write(" <td align='center'>");
document.write(" " + idx + "");
document.write(" </td>");
document.write(" </tr>");
document.write(" <tr>");
document.write(" <td class='label'>");
document.write(" <span> name part : " + idx + "</span>");
document.write(" </td>");
document.write(" </tr>");
document.write(" </table>");
document.write(" </td>");
if (cnt = 3)
{
document.write(" </tr>");
}
if (cnt = 3) {
cnt = 0;
}
}
document.write(" </table>");
</script>

You can try something like this:
var mytable = "<table cellpadding=\"0\" cellspacing=\"0\"><tbody><tr>";
for (var i = 1; i < 31; i++) {
if (i % 3 == 1 && i != 1) {
mytable += "</tr><tr>";
}
mytable += "<td>[" + i + "]</td>";
}
mytable += "</tr></tbody></table>";
document.write(mytable);
Here is a jsFiddle demo

This is untested psuedo-code, but may help you get started:
var x, row;
for(x=1;x<10;x=x+row)
{
document.write('<tr>');
for(row=0;row<2;row++)
{
document.write('<td>' + (x + row));
// Whatever else you want to output
}
}
Edit: this answer was given before OP edited his question to add additional info.

Use the modulo operator % to check for 3rd numbers and set the tags accordingly.
http://en.wikibooks.org/wiki/C_Sharp_Programming/Operators

Related

javascript undefined error - getting a value from a form

I'm a beginner! I started to study javascript, but there is an error what I can't find a way to solve it.
Uncaught TypeError: Cannot read property 'value' of undefined
at correct (homework.jsp:50)
at HTMLInputElement.onclick (homework.jsp:63)
It happens when I put the 'done' button. I wanted to get a value from a form. But the value is always 'undefined' and I couldn't change it to Number or String. Maybe I failed from getting the value. Could you kindly help me?
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<h2>Homework</h2>
<form name="gugu">
<script type="text/javascript">
//How many questions?
var size=eval(window.prompt("How many questions?"));
var a=new Array(size);
var b=new Array(size);
var ans=new Array(size);
var rst=new Array(size);
var count=0;
//Start
gugugu();
function gugugu() {
document.write("<table border='1'>");
for (var i=0; i<size+1; i++) {
if(i<size) {
document.write("<tr>");
document.write("<td>");
a[i]=parseInt(Math.random()*9)+1;
b[i]=parseInt(Math.random()*9)+1;
rst[i]=a[i]*b[i];
document.write(a[i]+"*"+b[i]+"=");
document.write("</td>");
document.write("<td>");
//I can't get the value!
var str="<input type='text' name='"+i+"'>";
document.write(str);
document.write("</td>");
document.write("</tr>");
} else {
document.write("<tr>");
document.write("<td colspan='2' align='center'>");
document.write("<input type='button' value='done' onclick='correct()'>");
document.write("<input type='button' value='reset' onclick='reset()'>");
document.write("</td>");
document.write("</tr>");
}
}
document.write("</table>");
document.write("count : ");
document.write("<input type='text' value='' name='count' readonly>");
document.write("<br>");
document.write("note : ");
document.write("<input type='text' value='' name='note' readonly>");
}
function correct() {
for (var i=0; i<size;i++) {
//Here I tried putting values into an Array, but 'undefined' happens!
ans[i]=String(document.gugu.i.value);
document.write(typeof(ans[i])+","+rst[i]+"<br>");
if(ans[i]==rst[i]) {
count=count+1;
}
}
document.gugu.count.value=eval(count);
document.gugu.note.value=eval(count*10);
}
function reset() {
clear();
gugugu();
}
</script>
</form>
"gugu" its the form name, document.gugu is undefined, because its not a global variable, to get the form: document.getElementsByName("gugu");
ans[i]=String(document.gugu.i.value);
then after getting the form (in an HTMLElement[] type), you are trying to get a row?, you cant do FORM.i, "i" has no context here, access it from the array ans[], this way you can get the value from the input by their name (numbers you set as name):
ans[i] = String(document.getElementsByName("" + i)[0].values[i]);
So with a few changes here and there this works:
<h2>Homework</h2>
<form name="gugu">
<script type="text/javascript">
//How many questions?
var size = eval(window.prompt("How many questions?"));
var a = new Array(size);
var b = new Array(size);
var ans = new Array(size);
var rst = new Array(size);
var count = 0;
//Start
gugugu();
function gugugu() {
document.write("<table border='1'>");
for (var i = 0; i < size + 1; i++) {
if (i < size) {
document.write("<tr>");
document.write("<td>");
a[i] = parseInt(Math.random() * 9) + 1;
b[i] = parseInt(Math.random() * 9) + 1;
rst[i] = a[i] * b[i];
document.write(a[i] + "*" + b[i] + "=");
document.write("</td>");
document.write("<td>");
var str = "<input type='text' name='in" + i + "'>";
document.write(str);
document.write("</td>");
document.write("</tr>");
} else {
document.write("<tr>");
document.write("<td colspan='2' align='center'>");
document.write("<input type='button' value='done' onclick='correct()'>");
document.write("<input type='button' value='reset' onclick='reset()'>");
document.write("</td>");
document.write("</tr>");
}
}
document.write("</table>");
document.write("count : ");
document.write("<input type='text' value='' name='count' readonly>");
document.write("<br>");
document.write("note : ");
document.write("<input type='text' value='' name='note' readonly>");
}
function correct() {
console.log("correct");
for (var i = 0; i < size; i++) {
ans[i] = parseInt(document.getElementsByName("in" + i)[0].value);
console.log(ans[i]);
console.log(rst[i]);
if (ans[i] === rst[i]) {
count = count + 1;
}
}
console.log(count);
document.getElementsByName("count")[0].value = count;
document.getElementsByName("note")[0].value = (count * 10);
}
function reset() {
clear();
gugugu();
}
</script>
</form>
I think you can't access html elements like this document.something. Check this to see the different ways to access html elements using JavaScript.

i want to create new table dynamically and removed it by same button using jquery?

I want to show updated rows no every time. I have this code .want to remove and generate again as this same
var table = $('#table').children();
for (var j = i; j < result.length; j++) {
table.append("<tr><td>" + (j + 1) + "</td><td><b>" + result[j].VoterName + "</b></td><td><b>" + result[j].VoterContact + "</b></td><td><button>X</button></td></tr>");
i++;
}
function createOrDeleteTable(){
console.log("wadawdawd");
if($("#btn").attr("created") === "false") {
$("#btn").attr("created","true");
var tabledata = "<table>"
+ "<tr>"
+"<th> hey </th>"
+"<th> hello </th>"
+ "</tr>"
+ "</table>";
console.log(tabledata);
$("#appendHere").html(tabledata);
} else {
$("#btn").attr("created","false");
$("#appendHere").html("");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="createOrDeleteTable();" created="false" id="btn"> create table </button>
<div id="appendHere"> </div>

Dynamically add <td>'s to a table

I am trying to create a table of 30 days of dates, starting from today.
right now I have this working, but it is being returned as a string.
I want to add a <td> with each date returned to my table.
My code is this
HTML
<table>
<tbody>
<tr>
<td></td> <!-- Add Each Date here -->
</tr>
</tbody>
</table>
JS
var date = moment(),
begin = moment(date).startOf('week').isoWeekday(1);
var str = "";
for (var i=0; i<30; i++) {
str += begin.format("MMM Do") + '<br>';
begin.add('days', 1);
}
// Would like to add date to each <td> and add <td> to the table
document.body.innerHTML = str;
DEMO
Just need slight addition to your existing code see below,
var date = moment(),
begin = moment(date).startOf('week').isoWeekday(1);
var str = [];
for (var i=0; i<30; i++) {
str.push('<td>' + begin.format("MMM Do") + '</td>');
begin.add('days', 1);
}
$('#myTable tbody').append('<tr>' + str.join('') + '</tr>');
DEMO: http://jsfiddle.net/wzdr2/
This should work:
for (var i=0; i<30; i++) {
$("table tr").append("<td>" + begin.format("MMM Do") + "</td>");
begin.add('days', 1);
}
Try not to append to DOM each time, it'l make it slower and inefficient especially if you have too many items to be appended. Instead add them up and append in the end.
var str = "", $tds= [];
for (var i=0; i<30; i++) {
$tds.push('<td>' + begin.format("MMM Do") + '</td>'); //push the tds to the temp array
begin.add('days', 1);
}
// Would like to add date to each <td> and add <td> to the table
$('table tr').append($tds); //append in the end
Demo
You could append them as you go. Like so...
http://jsfiddle.net/jzKMS/
for (var i=0; i<30; i++) {
$('#dates tbody').append('<tr><td>' + begin.format("MMM Do") + '</td></tr>');
begin.add('days', 1);
}
Or, for faster running, build your elements first and append once at the end.

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.

JavaScript continuously running in Firefox

I cannot figure out why my code continues to run even though it appears to have completely loaded the proper HTML. This problem only appears in Firefox (using ver. 3.5.3) and not in IE. This is just a simple script to display a multiplication table with a few decorative effects mixed in.
<html>
<head>
<title>Multiplication Table</title>
<script>
function drawTable(){
var rb = document.configForm.rowBegin.value - 1;
var re = document.configForm.rowEnd.value;
var cb = document.configForm.colBegin.value - 1;
var ce = document.configForm.colEnd.value;
document.write("Perfect squares are highlighted in red.<p>");
document.write("<table border=\"1\">");
for(i = rb; i <= re; i++){
document.write("<tr>");
for(j = cb; j <= ce; j++){
if(i == rb && j == cb){
// ignore top left corner
document.write("<td bgcolor=\"#ffffff\"></td>");
}
else if(i == rb){
// to display the column headers
if(j % 2 == 0)
document.write("<td align=\"center\" bgcolor=\"#99d9e0\">" + j + "</td>");
else
document.write("<td align=\"center\">" + j + "</td>");
}
else if(j == cb){
// to display the row headers
if(j % 2 == 0)
document.write("<td align=\"center\" bgcolor=\"#99d9e0\">" + i + "</td>");
else
document.write("<td align=\"center\">" + i + "</td>");
}
else{
// writes the solutions to the table
if(i == j || Math.sqrt(i*j) % 1 == 0)
// highlight the perfect squares
document.write("<td align=\"center\" bgcolor=\"#ff8080\">" + i * j + "</td>");
else if(j % 2 == 0)
document.write("<td align=\"center\" bgcolor=\"#99d9e0\">" + i * j + "</td>");
else
document.write("<td align=\"center\">" + i * j + "</td>");
}
}
document.write("</tr>");
}
document.write("</table>");
}
</script>
</head>
<body>
<h2>Multiplication Table</h2>
<form name="configForm">
Row Range:</br>
Begin <input type="text" name="rowBegin" size="5">
End <input type="text" name="rowEnd" size="5">
<p>
Column Range:</br>
Begin <input type="text" name="colBegin" size="5">
End <input type="text" name="colEnd" size="5">
<p>
<input type="Submit" value="Make Table" onclick="return drawTable()">
</form>
</body>
</html>
If you use document.write() you need to use document.close(); to tell the browser you are done.
Using something like alert(); can also stop the spinner from spinning but that isn't likely what you want.
add document.close(); to the end of the function. It appears that Firefox doesn't realize that you're done writing.

Categories

Resources