cant print rows in javascript when array is used - javascript

I am making a web page using HTML and js following is the code for that,
essentially I want to store the numbers generated by function and show it in column 6, so I am storing it in the array a and show it in column 6. But when I write to add the number for loop stops right there and control exits from the loop. ie. only one row and one column is displayed like
uid day time source destination bus
2
rand.html
<!DOCTYPE html>
<head>
<script type="text/javascript">
var abc = 0;
a = new Array();
var b = 0;
//Returns a random number
function CreateLottoValues()
{
return Math.floor(Math.random() * 20 + 1);
}
//create table
function UpdateTable()
{
document.write("<table border=1 id='myTable' > ")
document.write(" <tr><td > uid</td><td > day</td><td
> time</td><td > source</td><td > destination</td> <td
> bus</td></tr> ")
for (row=2; row<=30; row++) {
document.write("<tr>")
for (col=1; col<=6; col++) {
if(col==1){
document.write("<td >" +row+ "</td>")
}
else if(col==6){
for (var i = 0; i <= a.length; i++) {
document.write("<td>" + a[i] +"</td>")
}
}
else{
abc = CreateLottoValues();
a.add(abc);
//tmp =row + col;
//document.getElementById(tmp).innerHTML = CreateLottoValues();
document.write("<td >" + abc + "</td>")
}
}
document.write("</tr>")
}
document.write("</table>")
}
</script>
</head>
<body>
<center>
<div id="container">
<div id="header">
<h1>Welcome</h1>
<p id="demo"></p>
</div>
</div>
<input id="btn" type="button" value="Re-generate Numbers"
onClick="UpdateTable()" />
</center>
</body>
</html>
Can anyone help me? thank you for your suggestions.

On closer inspection, I found that your program won't run correctly because of this line:
a.add(abc);
This is because the variable a is an array, and to add elements to an array you use the push function
Replace a.add(abc) with a.push(abc). I've also made a few other changes which you can understand by comparing this with your code:
<!DOCTYPE html>
<head>
<script type="text/javascript">
var abc = 0;
a = new Array();
var b = 0;
//Returns a random number
function CreateLottoValues()
{
return Math.floor(Math.random() * 20 + 1);
}
//create table
function UpdateTable()
{
document.write("<table border=1 id='myTable' > ")
document.write(" <tr><td > uid</td><td > day</td><td> time</td><td > source</td><td > destination</td> <td> bus</td></tr> ")
for (row=2; row<=30; row++) {
document.write("<tr>")
for (col=1; col<=6; col++) {
if(col==1){
document.write("<td >" +row+ "</td>")
}
else if(col==6){
document.write("<td>");
for (var i = 0; i < a.length; i++) {
document.write(a[i])
}
document.write("</td>");
a = new Array();
}
else{
abc = CreateLottoValues();
a.push(abc);
//tmp =row + col;
//document.getElementById(tmp).innerHTML = CreateLottoValues();
document.write("<td >" + abc + "</td>")
}
}
document.write("</tr>")
}
document.write("</table>")
}
</script>
</head>
<body>
<center>
<div id="container">
<div id="header">
<h1>Welcome</h1>
<p id="demo"></p>
</div>
</div>
<input id="btn" type="button" value="Re-generate Numbers"
onClick="UpdateTable()" />
</center>
</body>
</html>

Related

Problem with modifying JavaScript/HTML code

I've got a problem with modifying my code. I need to edit my code so it will not only do its purpose (the thing that it does now) but it will count from 1 to given number.
The code is in Polish and it's simple. It's purpose for now is to calculate the factorial of given number.
Here's the code:
function obliczSilnie(liczba) {
var wynik = silnia(liczba);
if (wynik > 0) {
document.getElementById("result").innerHTML =
"<h3 style'color:blue;'>Silnia liczby " + liczba +
"wynosi: " + wynik + "</h3>";
}
}
function silnia(liczba) {
if (liczba == 0 || liczba == 1) {
return 1;
} else if (liczba < 0) {
error();
return -1;
}
var wynik = liczba * silnia(liczba - 1);
return wynik;
}
function error() {
document.getElementById("result").innerHTML =
"<h3 style='color:red;'>Błąd: Nie można obliczyć silni dla liczby ujemnej! </h3>";
}
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Obliczanie silni</h1>
<form name="myForm">
<p> <b>Podaj liczbę:</b>
<input type="number" name="myNumber" value="0" size=2> </p>
<input type="reset" value="Wyczyść">
<input type="button" value="Obilcz" onclick="obliczSilnie(document.myForm.myNumber.value)">
</form>
<p id="result"></p>
</body>
</html>
I hope I understood your question correctly. That's my solution:
function computeFactors(number) {
//Here we use recursion with a for loop
for(var i = 1;i < number;i++){
var result = factorial(i);
if (result > 0) {
document.getElementById("result").innerHTML +=
"<h3 style='color:blue;'> Factorial of " + i +
" is: " + result + "</h3>";
}
}
}
function factorial(number) {
if (number == 0 || number == 1) {
return 1;
} else if (number < 0) {
error();
return -1;
}
var result = number * factorial(number - 1);
return result;
}
function error() {
document.getElementById("result").innerHTML =
"<h3 style='color:red;'>Error: Could not factorize a negative number! </h3>";
}
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Factory calculation</h1>
<form name="myForm">
<p> <b>Enter a number:</b>
<input type="number" name="myNumber" value="0" size=2> </p>
<input type="reset" value="Clear">
<input type="button" value="Calculate" onclick="computeFactors(document.myForm.myNumber.value)">
</form>
<p id="result"></p>
</body>
</html>

Jquery & HTML - dynamically create div-table

Say I have a textfield where the dimensions of the table are given. like 2 3
now I need to write a function that creates a table out of div-tags with those dimensions. The table has to be inserted in the <div id="output"> -element
I was thinking of making a string with osme for-loops that looks like this
<div>
<div> </div>
<div> </div>
</div>
<div>
... (more columns)
</div>
So that looks like a sequence of div-tags and afterwards I would convert this to html and insert it.
But isn't there a more efficient way?
In your Javascript,
<script type="text/javascript">
var rows,cols,str="";
function generateTable()
{
rows = documnt.getElementById('rows').value;
cols = documnt.getElementById('cols').value;
str ="<table>"
for(var i=0;i<rows;i++)
{
str = str+"<tr>";
for(vat j=0;j<cols;j++)
{
str = str+"<td></td>";
}
str =str+"</tr>";
}
str = str + "</table>;
documnt.getElementById('output').innerHTML = str;
}
</script>
In your HTML,
<input type="number" id="rows" placeholder="Number of rows" />
<input type="number" id="cols" placeholder="Number of cols" />
<input type="button" id="submit" value="Submit" onClick="generateTable();" />
<br>
<br>
<div id="output"></div>
Something like this maybe:
var rows = 3; //these would be populated by your text field entries
var columns = 2;
function makeTable() {
html = '<table>';
for(var i=0; i<rows; i++) {
html += '<tr>';
for(var j=0; j<columns; j++) {
html += '<td><p>Some Data</p></td>';
}
html += '</tr>';
}
html += '</table>';
document.getElementById("output").innerHTML = html;
}
table, td {
border: 1px solid black; padding: 5px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Table Maker</title>
</head>
<body>
<div id="output" onClick="makeTable()"><h1>Click me to make a table!</h1></div>
</body>
</html>

Function's code displays at top of webpage

I am trying to get my function to display its executed code inside a div or a table.
At the moment the code is executed and displayed at the top of the page. I want it to display on a specific area on my page. how do i do this?
Here is my external scripts code, called "SquareScript.js":
function Display()
{
var a = document.getElementById("value1").value;
var b = document.getElementById("value2").value;
for(var i = 0; i < a; i++)
{
document.getElementById("Paragraph").innerHTML += " " +
document.getElementById("myValue").value;
}
document.getElementById("Paragraph").innerHTML += "<br>";
for (var r = 0; r < b; r++)
{
document.getElementById("Paragraph").innerHTML += " " +
document.getElementById("myValue").value;
for(var p = 0; p < a-2; p++)
{
document.getElementById("Paragraph").innerHTML += "&nbsp&nbsp&nbsp";
}
document.getElementById("Paragraph").innerHTML += " " +
document.getElementById("myValue").value;
document.getElementById("Paragraph").innerHTML += "<br>";
}
for(var i = 0; i < a; i++)
{
document.getElementById("Paragraph").innerHTML += " " +
document.getElementById("myValue").value;
}
}
My code generates a square on the page with the height and width that the user entered, also using the character the user entered.
Here is my main webpages code:
<head>
<link rel = "stylesheet" type = "text/css" href = "Assignment3.css">
<style>
table {background-color:black;color:white; align: center;}
body {background-image: url('squares.png');}
</style>
</head>
<title>Generate A Square</title>
<body>
<p Id="Paragraph"></p>
<div class = "heading">
<h1><img src = "Interested.png" width = 100px height = 100px></img>WELCOME TO BUILD A SQUARE</h1>
</div>
<table align = center>
<tr>
<td>
Please Enter value number 1:&nbsp&nbsp<input type = "text" id = "value1">
</td>
</tr>
<tr>
<td>
Please Enter value number 2:&nbsp&nbsp<input type = "text" id = "value2">
</td>
</tr>
<tr>
<td>
Enter a character for your square's border:&nbsp&nbsp<input type="text" Id="myValue"> </input>
</td>
</tr>
<tr>
<td>
<button onclick="Display()">Display</button>
</td>
</tr>
</table>
<div style = "margin-left: 45%;">
<button><a href = "MainMenu.html">Return To Main Menu</button>
<script src = "SquareScript.js" ></script>
</div>
</body>
as you can see i call my external script inside tags after my table. But it still displays at the top of the page.
What can I do to display my executed script inside the div tag which i put it in?
Thanks for any help or any suggestions!
Your script generates the square and places it inside
<p Id="Paragraph"></p>
To move the square to the div where you have the script tag, move the existing <p Id="Paragraph"></p> below the script tag. the div code will be
<div style = "margin-left: 45%;">
<button><a href = "MainMenu.html">Return To Main Menu</button>
<script src = "SquareScript.js" ></script>
<p Id="Paragraph"></p> <!-- move this p tag here -->
</div>

To validate dynamic elements in the table

I want to validate the dynamically created textarea, In the below mentioned code i can able to validate only the first row but i can't validate for the second row.How to validate/get all the row values.
Thanks in advance.
To create Dynamic elements click add question image.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title> new document </title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.1/jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready(function ()
{
var i = 0;
$("#AddQuestion").click(function ()
{
$("#NoQuestions").remove();
++i;
var IdCount = i + ".)";
var newRowContent = "<tr id='SQRow"+i+"'"+" ><td>" + IdCount + "</td>" + "<td><textarea id='txtQuestions" + i + "'" + "style='height: 45px;width: 420px'></textarea> </td>" + "<td><select id='ddlDataType" + i + "'" + " style='margin-left: 47px'><option value=''>Select Data Type</option><option value='int'>Numeric</option><option value='Varchar'>Alpha Numeric</option></select> </td>" + "<td><div ><a href='#'><img src='/Images/1363247672_document-edit.png' width='26' height='27' alt='EditButton'/> </a><a href='#'><img src='/Images/1363247321_Remove.png' alt='DeleteButton'/></a> </div> </br><div style='display: none'><a href='#'><img src='/Images/Accept-iconSmall.png' width='26' height='27' alt='UpdateButton'/></a><a href='#'><img src='/Images/Button-Cancel-icon.png' width='26' height='27' alt='CancelButton' /></a></td>" + "</tr>";
$("#tblSecurityQuestions").append(newRowContent);
});
$("#btnUpdateQuestions").click(function ()
{
var txtAreaVal = $('textarea').val().length;
var ddlDataType = $('#tblSecurityQuestions select').val().length;
alert(txtAreaVal);
alert(ddlDataType + "The ddl is " );
if (txtAreaVal <= 0)
{
alert('Please add Questions');
return;
} else if (ddlDataType <= 0)
{
alert('Please select the data type');
return;
}
});
});
</script>
</head>
<body>
<form id="SQPageForm" name="SQPageForm" method="post" action="">
<div id="SecurityQuestions" style="height: auto;border-color: #f00;border: 1.5px;border-style: dotted">
<h3>Configure Security Questions</h3>
<div id="AddNewSecurityQuestions" style="">
<p style="float: left;margin-top: 11px">Add Question </p>
<img id="AddQuestion" src="/Images/document-add-icon.png" alt="Add Questions" width="35px" height="35px" style="cursor: pointer"/>
</div>
</br>
Security Questions?
</br>
<table border="1" id="tblSecurityQuestions">
<tr>
<th style="width: 25px">
ID
</th>
<th style="width: 424px">
Security Questions
</th>
<th style="width: 210px">
DataType
</th>
<th style="width :65px">
Actions
</th>
</tr>
</table>
</div>
</br>
</br>
<input type="button" id="btnUpdateQuestions" value="Set Security Question" style="margin-left: 300px" />
</body>
</html>
Try
$("#btnUpdateQuestions").click(function() {
$('#tblSecurityQuestions tr:gt(0)').each(function() {
var $this = $(this);
var txtAreaVal = $('textarea', $this).val().length;
var ddlDataType = $('select', $this).val().length;
alert(txtAreaVal);
alert(ddlDataType + "The ddl is ");
if (txtAreaVal <= 0) {
alert('Please add Questions');
return;
} else if (ddlDataType <= 0) {
alert('Please select the data type');
return;
}
})
});
var textAreaSize = $('#tblSecurityQuestions tr:gt(1)').size();
for (var j = 1; j <= textAreaSize; j++)
{
var txtAreaVal = $('#txtQuestions' + j).val();
var ddlDataType = $('#ddlDataType' + j).val();
if (txtAreaVal <= 0)
{
alert('Please add Questions');
return;
} else if (ddlDataType <= 0)
{
alert('Please select the data type');
return;
}
}
I came up with a solution, it is working for me now
Try to iterate all text areas, then check the same condition:
for(var i=0; i<NoOfquestions; i++){
var txtAreaVal = $('#txtQuestions'+i).val().length;
var ddlDataType = $('#tblSecurityQuestions select').val().length;
alert(txtAreaVal);
alert(ddlDataType + "The ddl is");
if (txtAreaVal <= 0)
{
alert('Please add Questions');
return;
}
else if (ddlDataType <= 0)
{
alert('Please select the data type');
return;
}
}

Calling a function without clicking anything

I'm new in programming and I'm trying to call a function without any button or click event. I'm doing a table within a table using javascript function. Here's my code so far:
<html>
<head> <title> Hello </title> </head>
<body>
<table border=1>
<tr>
<td> Hello! <input type='hidden' value='0' id='theValue' /> <script> add(); </script> <div id='myDiv'> </div> </td>
</tr>
<script>
$ctra = 1;
$ctr1a = 1;
function add() {
var ni = document.getElementById('myDiv');
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value -1)+ 2;
numi.value = num;
var newdiv = document.createElement('div');
var divIdName = 'my'+num+'Div';
newdiv.setAttribute('id',divIdName);
newdiv.innerHTML = "<table border=1>"+
"<tr>"+
"<td> Hello! <input type='hidden' value='0' id='theValue' /> <script> add(); </script> <div id=('" + divIdName + "')> </div> </td>"+
"</tr>"+
"</table>";
if($ctra<100){
ni.appendChild(newdiv);
$ctra++;
}
}
</script>
</table>
</body>
</html>
When I run it, it displays
"+ ""+ "
Hello!
"; if($ctra<100){ ni.appendChild(newdiv); $ctra++; } }
in the browser. What could the problem be? Thank you in advance!
EDIT
function add() {
var ni = document.getElementById('myDiv');
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value -1)+ 2;
numi.value = num;
var newdiv = document.createElement('div');
var divIdName = 'my'+num+'Div';
newdiv.setAttribute('id',divIdName);
newdiv.innerHTML = "<table border=1><tr><td> Hello! <input type='hidden' value=0 id='theValue' /><div id='" + divIdName + "'></td></tr></table>";
ni.appendChild(newdiv);
for(var i=1;i<100;i++) {
var ni = document.getElementById(divIdName);
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value -1)+ 2;
numi.value = num;
var newdiv = document.createElement('div');
var divIdName = 'my'+num+'Div';
newdiv.setAttribute('id',divIdName);
newdiv.innerHTML = "<table border=1><tr><td> Hello! <input type='hidden' value='" + i + "' id='theValue' /><div id='" + divIdName + "'></td></tr></table>";
ni.appendChild(newdiv);
}
}
Try this
<html>
<head> <title> Hello </title> </head>
<script type="text/javascript">
$ctra = 1;
$ctr1a = 1;
function add() {
alert('s')
var ni = document.getElementById('myDiv');
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value -1)+ 2;
numi.value = num;
var newdiv = document.createElement('div');
var divIdName = 'my'+num+'Div';
newdiv.setAttribute('id',divIdName);
newdiv.innerHTML = "<table border=1><tr><td> Hello! <input type='hidden' value='0' id='theValue' /></tr></table>";
if($ctra<100){
ni.appendChild(newdiv);
$ctra++;
}
}
</script>
<body onload="add()">
<table border="1">
<tr>
<td> Hello! <input type='hidden' value='0' id='theValue' />
<div id='myDiv'> </div> </td>
</tr>
</table>
</body>
</html>
Hope it works for you..:)
Your JS results in nested blocks, this isn't allowed in html. The function add() in your blocks is not defined, because when the browser encounters it, it hasn't seen your definition of add() yet. Your table contains a script that contains another table which contains yet another script. It's very confusing :P
OK, if i understand correctly: you have a single table. You'd like to have JS put another table inside. The thing you want to put inside is, in this example, a copy of the table. You want to end up with a table inside a table and you want to achieve it programatically.
First separate your concerns: scripts and html:
If you put your add() after the definition and you put your script after the body then the browser will encounter it and run it. HTH:
<html>
<head> <title> Hello </title> </head>
<body>
<table id="t1" border=1>
<tr>
<td> Hello! <input type='hidden' value='0' id='theValue' />
<div id='myDiv'></div>
</td>
</tr>
</table>
<script>
function add_table() {
var table1 = document.getElementById("t1"),
table2 = table1.cloneNode(true),
mydiv = document.getElementById("myDiv"),
mydiv2;
table2.setAttribute('id', 't2');
mydiv2 = table2.getElementsByTagName("div")[0];
mydiv2.setAttribute('id', 'myDiv2');
mydiv.appendChild(table2);
}
// call the function
add_table();
</script>
</body>
</html>
You have </script> inside the code. Browser interprets that as an end of javascript and breaks back to HTML. To fix this, you can divide this string into for example </sc'+'ript>. That will fix this issue, but probably you'll still have to work a bit on the script, but that's a different story.
You have to switch between differents quotes, and remove braces for the id, like this :
newdiv.innerHTML = "<table border=1>"
+"<tr>"
+'<td> Hello! <input type="hidden" value="0" id="theValue" /> '
+'<script> add(); </script> <div id="' + divIdName + '"> </div> </td>'
+"</tr>"
+"</table>";
Because you cant access the function without any evnt in the dom..You have to call the function on any event of the elemnt.
move the script outside the table-element to the head or to the end of the body.
first add the div, then call the script. you might want to call your add() in <body onload='add'>
remove the braces here to create valid html: <div id=('" + divIdName + "')>

Categories