javascript undefined error - getting a value from a form - javascript

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.

Related

How can I change the initial value on JavaScript

For example I have an initial value of 10,000 when I click the radio button which is "Minus" and I enter a value of 1000 the initial value will become 9000. And when I click the radio button "Add" and I enter a value of 2000
current initial which is 9000 + 2000 is equal to 11,000.
The problem is the initialValue back to it's original value which is 10,000.
//external script
function Compute(initialNum, numOne) {
this._initialNum = initialNum;
this._numOne = numOne;
this.addNum = function() {
alert(this._initialNum = this._initialNum + this._numOne);
return this._initialNum;
};
this.minusNum = function() {
alert(this._initialNum = this._initialNum - this._numOne);
return this._initialNum;
};
}
//body script
var rdoAdd = document.getElementById("rdoAdd");
var rdoMinus = document.getElementById("rdoMinus");
var tblResult = document.getElementById("tblResult");
function printResult() {
var initialValue = 10000, deposit = 0, withdraws = 0;
var rdoAdd = document.getElementById("rdoAdd");
var rdoMinus = document.getElementById("rdoMinus");
var numOne = parseInt(document.getElementById('txtNumOne').value);
var objAccount = new Compute(initialValue, numOne);
if (rdoAdd.checked) {
deposit += objAccount.addNum();
display = "<tr>";
display += "<td>" + deposit + "</td>";
display += "<tr>";
tblResult.innerHTML += display;
resetx();
} else {
withdraws += objAccount.minusNum();
display = "<tr>";
display += "<td>" + withdraws + "</td>";
display += "<tr>";
tblResult.innerHTML += display;
resetx();
}
}
function resetx() {
document.getElementById('txtNumOne').value = "";
document.getElementById("rdoAdd").checked = false;
document.getElementById("rdoMinus").checked = false;
}
<input type="radio" id="rdoAdd" name="rdo" required>Add<br><br>
<input type="radio" id="rdoMinus" name="rdo" reuired>Minus<br><br>
<input type="text" id="txtNumOne"><br><br>
<!--
Withdraw<br><br>
<input type="text" id="txtNumTwo">
-->
<button onclick="printResult()">Compute</button><br><br>
<table border="1px">
<th>Result</th>
<tbody id = "tblResult">
</tbody>
</table>
Just move
var initialValue = 10000;
var objAccount = new Compute(initialValue);
outside of the printResult function.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<input type="radio" id="rdoAdd" name="rdo" required>Add<br><br>
<input type="radio" id="rdoMinus" name="rdo" reuired>Minus<br><br>
<input type="text" id="txtNumOne"><br><br>
<button onclick="printResult()">Compute</button><br><br>
<table border="1px">
<th>Result</th>
<tbody id = "tblResult">
</tbody>
</table>
<script src = "java.js"></script>
<script>
var rdoAdd = document.getElementById("rdoAdd");
var rdoMinus = document.getElementById("rdoMinus");
var tblResult = document.getElementById("tblResult");
var initialValue = 10000;
var objAccount = new Compute(initialValue);
function printResult() {
var display = "";
var rdoAdd = document.getElementById("rdoAdd");
var rdoMinus = document.getElementById("rdoMinus");
var numOne = parseInt(document.getElementById('txtNumOne').value);
if (rdoAdd.checked) {
objAccount.addNum(numOne); // This will directly adjust `initialValue`
display = "<tr>";
display += "<td>" + objAccount._initialValue + "</td>";
display += "<tr>";
tblResult.innerHTML += display;
resetx();
} else {
objAccount.minusNum(numOne); // This will directly adjust `initialValue`
display = "<tr>";
display += "<td>" + objAccount._initialValue + "</td>";
display += "<tr>";
tblResult.innerHTML += display;
resetx();
}
}
function resetx() {
document.getElementById('txtNumOne').value = "";
document.getElementById("rdoAdd").checked = false;
document.getElementById("rdoMinus").checked = false;
}
</script>
</body>
</html>
function Compute(initialNum) {
this._initialNum = initialNum;
this.addNum = function(numOne) {
alert(this._initialNum = this._initialNum + numOne);
return this._initialNum;
};
this.minusNum = function(numOne) {
alert(this._initialNum = this._initialNum - numOne);
return this._initialNum;
};
}
This is just a scope related issue. If you use var inside the function, it'll redeclare or create a new instance of initialValue in local scope.
If you want to change the value of variable initialValue, then don't use var. This will only change the variable defined in the global scope...
This works since the JavaScript interpreter firstly checks if there is an instance of the given variable in the local scope or not. If not, then it will check the existence of the variable in global scope.
EDIT :
As per your problem, you want the value of initialValue to persist after each calculation. In order to achieve this, you must first declare the object objAccount in the global scope outside the printResult() function; since in the code, every time the function printValue() is called, a new instance of Compute (objAccount) is being created. Secondly, you should remove the numOne attribute from Compute class and instead pass numOne as a parameter to addNum() and minusNum().
You can modify the methods of Compute as:
this.addNum = function(_numOne) {
...
}
this.minusNum = function(_numOne) {
...
}
And while calling the methods,
objAccount.addNum(<some_number>);
and
objAccount.minusNum(<some_number>);
After this, you need not even use deposit or withdraws...
if (rdoAdd.checked) {
objAccount.minusNum(numOne); // This will directly adjust `initialValue`
display = "<tr>";
display += "<td>" + objAccount._initialNum + "</td>";
display += "<tr>";
tblResult.innerHTML += display;
resetx();
}
Similarly, do the same with the else statement...
Bonus: You seem to be using ES5 style, instead use ES6 (includes keywords like class & let: similar to var)
Here's a snippet (using ES6 classes)
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<input type="radio" id="rdoAdd" name="rdo" required>Add<br><br>
<input type="radio" id="rdoMinus" name="rdo" reuired>Minus<br><br>
<input type="text" id="txtNumOne"><br><br>
<button onclick="printResult()">Compute</button><br><br>
<table border="1px">
<th>Result</th>
<tbody id = "tblResult">
</tbody>
</table>
<script src = "java.js"></script>
<script>
class Compute {
constructor(initialNum) {
this._initialNum = initialNum;
}
addNum(_numOne) {
alert(this._initialNum += _numOne);
return this._initialNum;
};
minusNum(_numOne) {
alert(this._initialNum -= _numOne);
return this._initialNum;
};
}
var rdoAdd = document.getElementById("rdoAdd");
var rdoMinus = document.getElementById("rdoMinus");
var tblResult = document.getElementById("tblResult");
var initialValue = 10000;
var objAccount = new Compute(initialValue);
function printResult() {
var display = "";
var rdoAdd = document.getElementById("rdoAdd");
var rdoMinus = document.getElementById("rdoMinus");
var numOne = parseInt(document.getElementById('txtNumOne').value);
if (rdoAdd.checked) {
objAccount.addNum(numOne); // This will directly adjust `initialValue`
display = "<tr>";
display += "<td>" + objAccount._initialNum + "</td>";
display += "<tr>";
tblResult.innerHTML += display;
resetx();
} else {
objAccount.minusNum(numOne); // This will directly adjust `initialValue`
display = "<tr>";
display += "<td>" + objAccount._initialNum + "</td>";
display += "<tr>";
tblResult.innerHTML += display;
resetx();
}
}
function resetx() {
document.getElementById('txtNumOne').value = "";
document.getElementById("rdoAdd").checked = false;
document.getElementById("rdoMinus").checked = false;
}
</script>
</body>
</html>

Javascript wrong variable type

Hello I'm preparing little guessing word game.
Somehow the type of my variable get changed from string to obj type what causes an Uncaught TypeError.
Here is a fragment of code:
let passwordArray = ["Java Script Developer", "FrontEnd"];
let sample = passwordArray[Math.floor((Math.random() *
passwordArray.length))];
let password = sample.toUpperCase();
let new_password = "";
for(let x =0; x<password.length;x++){
if(password[x]===" "){new_password += " "}
else{new_password += "-"}
}
$("#password span").text(new_password);
This part works correclty problem appears when I want to repalce a letter
String.prototype.replaceAt = function(index, replacement){
return this.substr(0,index) + replacement + this.substr(index + replacement.length)
};
function check(num) {
let test = false;
let temp = $(event.target).val();
if(password.indexOf(temp)>-1){test=true; /*alert(test +"/"+temp+"/"+password)*/}
$("#"+num).attr("disabled", true);
if(test === true) {
$("#"+num).removeClass("letter").addClass("hitletter");
let indeksy =[];
for(let i =0; i<password.length;i++ ){
if(password.charAt(i) === temp){indeksy.push(i)}
}
for(let x=0; x<indeksy.length;x++) {
let indx = indeksy[x];
new_password = new_password.replaceAt(indx, temp);
}
$("#password").html(new_password);
}};
My HTML basically is just:
<nav>
<input type="button" value="o mnie" id="me">
<input type="button" value="kalkulator" id="cal">
<input type="button" value="Wisielec" id="wis">
<input type="button" value="Memory" id="mem">
</nav>
<div id="content"></div>
Rest is dynamically added in JS:
$(function() {
$("#wis").click(function () {
$("#content").empty().append("" +
"<div id='container'>\n" +
"<div id='password'><span>Sample text</span></span></div>\n" +
"<div id='counter'>Counter: <span id='result'></span></div>\n" +
"<div id='gibbet' class='image'></div>\n" +
"<div id='alphabet'></div>\n" +
"<div id='new'>\n" +
"<input type='text' id='new_password'/>\n" +
"<button id='add' onclick='newPass()'>Submit</button>\n" +
"</div>\n" +
"</div>"
);
start();
});
});
function start(){
let new_password = "";
$("#contetn").empty();
let letters = "";
for(let i=0; i<32; i++){
letters += "<input class='letter' type='button' value='"+litery[i]+"' onclick='check("+i+")' id='"+i+"'/>"
}
$("#alphabet").html(letters);
$("#result").text(mistakeCounter);
for(let x =0; x<password.length;x++){
if(password[x]===" "){new_password += " "}
else{new_password += "-"}
}
$("#password span").text(new_password);
}
The problem is that variable new_password is somehow changing from type string to type object when i want to use function replaceAt()
looking at your code, with the new String.prototype.replaceAt this error can happen on 2 situations:
when the variable that uses replaceAt is not a string, example:
null.replaceAt(someIndex,'someText');
{}.replaceAt(someIndex,'someText');
[].replaceAt(someIndex,'someText');
the other situation is when you pass null or undefined as replacement:
"".replaceAt(someIndex,undefined);
"".replaceAt(someIndex,null);
just add some verification code and should be working good

Looping through text boxes, using id as a variable?

Basically I'm trying to populate an array with some values in text boxes. I thought I could do it by incrementing though ids, but it isn't working.
Here it is:
var sections = 0;
var mod = [];
var identifier = 0;
function addSection(){
sections++;
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'> <br>";
}
function removeSection(){
if (sections > 0){
sections--;
identifier -= 3;
document.getElementById("input").innerHTML = "";
for(i=0; i<sections; i++){
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'> <br>";
}
}
}
function calculate(){
populateArray();
}
function populateArray(){
var i,j;
for(i=0;i<sections * 3;i++){
var pop = i.toString();
mod[i] = parseInt(document.getElementById(pop).innerHTML.value);
i++;
pop = i.toString();
mod[i] = parseInt(document.getElementById(pop).innerHTML.value);
i++
pop = i.toString();
mod[i] = parseInt(document.getElementById(pop).innerHTML.value);
}
document.getElementById("debug").innerHTML = mod.toString();
}
<!doctype html>
<html>
<head>
<title>To Pass v1.0</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<h1>TO PASS</h1>
<button onclick="addSection()">Add Section</button>
<button onclick="removeSection()">Remove Section</button>
<div id='input'></div>
<button onclick="calculate()">Calculate</button>
<div id='output'></div>
<div id='debug'></div>
</body>
<script type="text/javascript" src="js/main.js"></script>
</html>
Is it possible doing it my method, or will it inevitably not work for whatever reason? Doing some searches it seems jquery might be the way to go, but I'm not sure how to get started with that.
jQuery certainly simplifies things, but it can't do anything that JavaScript can't do, and many amazing websites were built long before jQuery came into existence.
In populateArray(), remove innerHTML here:
mod[i] = parseInt(document.getElementById(pop).innerHTML.value);
Should be:
mod[i] = parseInt(document.getElementById(pop).value);
You can simplify the function like this:
function populateArray() {
var i;
for(i = 0 ; i < sections * 3 ; i++) {
mod[i] = parseInt(document.getElementById(i).value);
}
document.getElementById('debug').innerHTML = mod.toString();
}
In addSection(), this wipes out the values of existing input elements:
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
Instead, you should create new input elements and append them.
Here's a rewrite of the function:
var input= document.getElementById('input');
function addSection(){
var inp, i;
sections++;
for(var i = 0 ; i < 3 ; i++) {
inp= document.createElement('input');
inp.type= 'text';
inp.id= identifier++;
input.appendChild(inp);
}
input.appendChild(document.createElement('br'));
} //addSection
In removeSection(), values of all input elements are wiped out.
Instead of rewriting that function, I've done a complete rewrite or your program, without any global variables and without assigning IDs to the input elements.
If you have any questions, I'll update my answer with explanations.
Snippet
function addSection() {
var input= document.getElementById('input'),
sect= document.querySelector('section');
input.appendChild(sect.cloneNode(true));
}
function removeSection() {
var input= document.getElementById('input'),
sects= document.querySelectorAll('section');
if(sects.length > 1) {
input.removeChild(sects[sects.length-1]);
}
}
function calculate() {
var inp= document.querySelectorAll('section input'),
debug= document.getElementById('debug'),
mod= [],
i,
val;
for(i = 3 ; i < inp.length ; i++) {
val= parseInt(inp[i].value);
mod.push(val || 0);
}
debug.innerHTML = mod.toString();
}
section:first-of-type {
display: none;
}
<button onclick="addSection()">Add Section</button>
<button onclick="removeSection()">Remove Section</button>
<div id='input'>
<section>
<input type="text">
<input type="text">
<input type="text">
</section>
</div>
<button onclick="calculate()">Calculate</button>
<div id='output'></div>
<div id='debug'></div>
This version of your script stores the actual elements in an array of sections. That way you can loop through them as you would an array, and alter the contents that way.
Here's a pen of the code: looping through added elements
var sections = [];
var output = document.getElementById('input');
function addSection(){
var section = document.createElement('div');
for (var i = 0; i < 3; i++) {
el = document.createElement('input');
el.type = 'text';
section.appendChild(el);
}
sections.push(section);
output.appendChild(section);
}
function removeSection(){
if (sections.length > 0){
output.removeChild(sections.pop())
}
}
function calculate(){
populateArray();
}
function populateArray(){
for (var i = 0; i < sections.length; i++) {
for (var j = 0; j < sections[i].children.length; j++ ) {
sections[i].children[j].value = (i+1) * (j+2);
}
}
}
If your problem is the NaN, this is because you select an input field and then first try to read its innerHtml before reading its value. Read values of inputs directly.
var sections = 0;
var mod = [];
var identifier = 0;
function addSection(){
sections++;
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'> <br>";
}
function removeSection(){
if (sections > 0){
sections--;
identifier -= 3;
document.getElementById("input").innerHTML = "";
for(i=0; i<sections; i++){
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'>";
document.getElementById("input").innerHTML += "<input type='text' id='" + identifier++ + "'> <br>";
}
}
}
function calculate(){
populateArray();
}
function populateArray(){
var i,j;
for(i=0;i<sections * 3;i++){
var pop = i.toString();
mod[i] = parseInt(document.getElementById(pop).value);
i++;
pop = i.toString();
mod[i] = parseInt(document.getElementById(pop).value);
i++
pop = i.toString();
mod[i] = parseInt(document.getElementById(pop).value);
}
document.getElementById("debug").innerHTML = mod.toString();
}
<!doctype html>
<html>
<head>
<title>To Pass v1.0</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<h1>TO PASS</h1>
<button onclick="addSection()">Add Section</button>
<button onclick="removeSection()">Remove Section</button>
<div id='input'></div>
<button onclick="calculate()">Calculate</button>
<div id='output'></div>
<div id='debug'></div>
</body>
<script type="text/javascript" src="js/main.js"></script>
</html>

How to call to a function, with a string

i am creating a string from all the headlines of a table, that making a checkbox to each headline, and its should hide the col if its unchecked and show if its checked.
the function put all the checkbox in a div.
i am calling the function when the page is loaded (onload in the body)
this is my function:
function getFirstRow(table) {
var table = document.getElementById(table);
var row = table.getElementsByTagName('tr')[0];
var cells = row.getElementsByTagName('th');
var str = "";
for (var i=0; i < cells.length; i++) {
str += "<input type='checkbox' onclick='hideOrShowCol('TreesTable', "+i+", this);' checked='checked' />" + cells[i].innerHTML + " ";
}
document.getElementById("hideAndShow").innerHTML = str;
}
and this is the hide/show function:
function hideOrShowCol(table, col, e) {
alert(e.checked);
var ifToShow = "";
if (e.checked)
ifToShow = "table-cell";
else
ifToShow = "none";
var getTable = document.getElementById(table);
var tds = getTable.getElementsByTagName("tr");
for (var i = 0; i < tds.length; i++) {
tds[i].childNodes[col].style.display = ifToShow;
}
}
so the problem is that it is not calling to the function when i am creating the check boxes with the first function, but when i am writing directly in the html its works fine, like this:
<input type="checkbox" onclick="hideOrShowCol('TreesTable', 2, this);" checked="checked" />
some one know what its can be?? i tried everything...
thanks.
"<input type='checkbox' onclick='hideOrShowCol('TreesTable', "+i+", this);' checked='checked' />" is invalid because of the single quotes areound 'TreesTable' nested inside the single quote for the onclick.
Try changing to "<input type='checkbox' onclick='hideOrShowCol(\"TreesTable\", "+i+", this);' checked='checked' />"
try closing over 'i' and passing it to an anonymous self-invoking function:
for (var i=0; i < cells.length; i++) {
(function(indx) {
str += "<input type='checkbox' onclick='hideOrShowCol('TreesTable', "+indx+", this);' checked='checked' />" + cells[indx].innerHTML + " ";
})(i);
}

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