My javascript calculator doesn't work - javascript

I am trying to create a web calculator utilizing values of text input as numbers and replacing a label at the bottom with the result. Although the problem I am facing is that the functions are either not being called or some other stuff. I am just starting out on Javascript, if you guys would point the problem out, I'll be much grateful.
<!DOCTYPE html>
<html>
<head>
<title>Calc+</title>
<link rel="stylesheet" href="calculator.css">
</head>
<body>
<header>
<div class="container"><center><p><strong>Tarun's</strong>|Calculator</p>
</center></div>
</header>
<section id="calculator">
<div class="container">
<table id="inputs"><tr>
<td><input type="text" id="firstnumber"></td>
<td><input type="text" id="secondnumber"></td>
</tr>
</table>
<table id="operators" cellpadding="0" cellspacing="7">
<tr>
<td id="plus"><button onClick="addition()">+</button></td>
<td id="minus"><button onClick="difference()">-</button></td>
</tr>
<tr><td id="multiply"><button onClick="multiplication()">*</button></td>
<td id="divide"><button onClick="division()">/</button></td></tr>
<tr>
<td colspan="2"><center><label id="result">result</label></center></td>
</tr>
</table>
</div>
</section>
</body>
</html>
function additon()
{
var a = document.getElementById('firstnumber').value;
var b = document.getElementById('secondnumber').value;
document.getElementById("result") = a + b;
}
function difference()
{
var a = document.getElementById('firstnumber').value;
var b = document.getElementById('secondnumber').value;
document.getElementById("result").innerHTML = a - b;
}
function multiplication()
{
var a = document.getElementById('firstnumber').value;
var b = document.getElementById('secondnumber').value;
document.getElementById("result").innerHTML = a * b;
}
function division()
{
var a = document.getElementById('firstnumber').value;
var b = document.getElementById('secondnumber').value;
document.getElementById("result").innerHTML = a / b;
}

There are four major problems with your code.
First the whole JavaScript code (starting with "function addition()") is not inside a script tag. Currently it just gets interpreted as text, thats the reason why you should see it at the bottom when you load your side. To fix this you have to embed the code inside a script tag. The easiest way to do this is inside the head tag as follows:
<!DOCTYPE html>
<html>
<head>
<title>Calc+</title>
<link rel="stylesheet" href="calculator.css">
<script>
function additon()
//other functions here
</script>
</head>
<body>
Second the addition function does not set the innerHTML. Just set the innerHTML there like you did with the other functions.
Third, if you get the value as you try it, the type is actually a string. If you do string + string, the result is a concatination. So "1" + "1" = "11". To change this, just add a + before the a in the addition case, as follows
document.getElementById("result").innerHTML = +a + b;
(Thanks to Frederik Hansen who pointed that one out in the comments.)
Fourth, the addition function isn't named correctly. You wrote additon but you meant addition.

Related

How to get all unique characters represantations out of an utf-8 string in Firefox 70?

The result of the following code is only πŸ§œπŸ½β€β™‚οΈ πŸΎπŸΏπŸ›€πŸ›ŒπŸ»πŸΌπŸ§‘πŸ€πŸ‘­πŸ‘©πŸ‘«πŸ‘¨πŸ‘¬, where I want to find all the unique graphic represationations shown in the Firefox output that I copied to the var a originally. (Basically the code should show the original a string as output.)
How to do that?
<html>
<head>
<meta charset="UTF-8" />
<script>
var a = 'πŸ§œπŸ½β€β™‚οΈ πŸ§œπŸΎβ€β™‚οΈ πŸ§œπŸΏβ€β™‚οΈ πŸ§œπŸ›€πŸΏ πŸ›ŒπŸ» πŸ›ŒπŸΌ πŸ›ŒπŸ½ πŸ›ŒπŸΎ πŸ›ŒπŸΏ πŸ§‘πŸ»β€πŸ€β€πŸ§‘πŸ» πŸ§‘πŸ»β€πŸ€β€πŸ§‘πŸΌ πŸ§‘πŸ»β€πŸ€β€πŸ§‘πŸ½ πŸ§‘πŸ»β€πŸ€β€πŸ§‘πŸΎ πŸ§‘πŸ»β€πŸ€β€πŸ§‘πŸΏ πŸ§‘πŸΌβ€πŸ€β€πŸ§‘πŸ» πŸ§‘πŸΌβ€πŸ€β€πŸ§‘πŸΌ πŸ§‘πŸΌβ€πŸ€β€πŸ§‘πŸ½ πŸ§‘πŸΌβ€πŸ€β€πŸ§‘πŸΎ πŸ§‘πŸΌβ€πŸ€β€πŸ§‘πŸΏ πŸ§‘πŸ½β€πŸ€β€πŸ§‘πŸ» πŸ§‘πŸ½β€πŸ€β€πŸ§‘πŸΌ πŸ§‘πŸ½β€πŸ€β€πŸ§‘πŸ½ πŸ§‘πŸ½β€πŸ€β€πŸ§‘πŸΎ πŸ§‘πŸ½β€πŸ€β€πŸ§‘πŸΏ πŸ§‘πŸΎβ€πŸ€β€πŸ§‘πŸ» πŸ§‘πŸΎβ€πŸ€β€πŸ§‘πŸΌ πŸ§‘πŸΎβ€πŸ€β€πŸ§‘πŸ½ πŸ§‘πŸΎβ€πŸ€β€πŸ§‘πŸΎ πŸ§‘πŸΎβ€πŸ€β€πŸ§‘πŸΏ πŸ§‘πŸΏβ€πŸ€β€πŸ§‘πŸ» πŸ§‘πŸΏβ€πŸ€β€πŸ§‘πŸΌ πŸ§‘πŸΏβ€πŸ€β€πŸ§‘πŸ½ πŸ§‘πŸΏβ€πŸ€β€πŸ§‘πŸΎ πŸ§‘πŸΏβ€πŸ€β€πŸ§‘πŸΏ πŸ‘­πŸ» πŸ‘©πŸ»β€πŸ€β€πŸ‘©πŸΌ πŸ‘©πŸ»β€πŸ€β€πŸ‘©πŸ½ πŸ‘©πŸ»β€πŸ€β€πŸ‘©πŸΎ πŸ‘©πŸ»β€πŸ€β€πŸ‘©πŸΏ πŸ‘©πŸΌβ€πŸ€β€πŸ‘©πŸ» πŸ‘­πŸΌ πŸ‘©πŸΌβ€πŸ€β€πŸ‘©πŸ½ πŸ‘©πŸΌβ€πŸ€β€πŸ‘©πŸΎ πŸ‘©πŸΌβ€πŸ€β€πŸ‘©πŸΏ πŸ‘©πŸ½β€πŸ€β€πŸ‘©πŸ» πŸ‘©πŸ½β€πŸ€β€πŸ‘©πŸΌ πŸ‘­πŸ½ πŸ‘©πŸ½β€πŸ€β€πŸ‘©πŸΎ πŸ‘©πŸ½β€πŸ€β€πŸ‘©πŸΏ πŸ‘©πŸΎβ€πŸ€β€πŸ‘©πŸ» πŸ‘©πŸΎβ€πŸ€β€πŸ‘©πŸΌ πŸ‘©πŸΎβ€πŸ€β€πŸ‘©πŸ½ πŸ‘­πŸΎ πŸ‘©πŸΎβ€πŸ€β€πŸ‘©πŸΏ πŸ‘©πŸΏβ€πŸ€β€πŸ‘©πŸ» πŸ‘©πŸΏβ€πŸ€β€πŸ‘©πŸΌ πŸ‘©πŸΏβ€πŸ€β€πŸ‘©πŸ½ πŸ‘©πŸΏβ€πŸ€β€πŸ‘©πŸΎ πŸ‘­πŸΏ πŸ‘«πŸ» πŸ‘©πŸ»β€πŸ€β€πŸ‘¨πŸΌ πŸ‘©πŸ»β€πŸ€β€πŸ‘¨πŸ½ πŸ‘©πŸ»β€πŸ€β€πŸ‘¨πŸΎ πŸ‘©πŸ»β€πŸ€β€πŸ‘¨πŸΏ πŸ‘©πŸΌβ€πŸ€β€πŸ‘¨πŸ» πŸ‘«πŸΌ πŸ‘©πŸΌβ€πŸ€β€πŸ‘¨πŸ½ πŸ‘©πŸΌβ€πŸ€β€πŸ‘¨πŸΎ πŸ‘©πŸΌβ€πŸ€β€πŸ‘¨πŸΏ πŸ‘©πŸ½β€πŸ€β€πŸ‘¨πŸ» πŸ‘©πŸ½β€πŸ€β€πŸ‘¨πŸΌ πŸ‘«πŸ½ πŸ‘©πŸ½β€πŸ€β€πŸ‘¨πŸΎ πŸ‘©πŸ½β€πŸ€β€πŸ‘¨πŸΏ πŸ‘©πŸΎβ€πŸ€β€πŸ‘¨πŸ» πŸ‘©πŸΎβ€πŸ€β€πŸ‘¨πŸΌ πŸ‘©πŸΎβ€πŸ€β€πŸ‘¨πŸ½ πŸ‘«πŸΎ πŸ‘©πŸΎβ€πŸ€β€πŸ‘¨πŸΏ πŸ‘©πŸΏβ€πŸ€β€πŸ‘¨πŸ» πŸ‘©πŸΏβ€πŸ€β€πŸ‘¨πŸΌ πŸ‘©πŸΏβ€πŸ€β€πŸ‘¨πŸ½ πŸ‘©πŸΏβ€πŸ€β€πŸ‘¨πŸΎ πŸ‘«πŸΏ πŸ‘¬πŸ» πŸ‘¨πŸ»β€πŸ€β€πŸ‘¨πŸΌ πŸ‘¨πŸ»β€πŸ€β€πŸ‘¨πŸ½ πŸ‘¨πŸ»β€πŸ€β€πŸ‘¨πŸΎ πŸ‘¨πŸ»β€πŸ€β€πŸ‘¨πŸΏ πŸ‘¨πŸΌβ€πŸ€β€πŸ‘¨πŸ» πŸ‘¬πŸΌ πŸ‘¨πŸΌβ€πŸ€β€πŸ‘¨πŸ½ πŸ‘¨πŸΌβ€πŸ€β€πŸ‘¨πŸΎ πŸ‘¨πŸΌβ€πŸ€β€πŸ‘¨πŸΏ πŸ‘¨πŸ½β€πŸ€β€πŸ‘¨πŸ» πŸ‘¨πŸ½β€πŸ€β€πŸ‘¨πŸΌ πŸ‘¬πŸ½ πŸ‘¨πŸ½β€πŸ€β€πŸ‘¨πŸΎ πŸ‘¨πŸ½β€πŸ€β€πŸ‘¨πŸΏ πŸ‘¨πŸΎβ€πŸ€β€πŸ‘¨πŸ» πŸ‘¨πŸΎβ€πŸ€β€πŸ‘¨πŸΌ πŸ‘¨πŸΎβ€πŸ€β€πŸ‘¨πŸ½ πŸ‘¬πŸΎ πŸ‘¨πŸΎβ€πŸ€β€πŸ‘¨πŸΏ πŸ‘¨πŸΏβ€πŸ€β€πŸ‘¨πŸ» πŸ‘¨πŸΏβ€πŸ€β€πŸ‘¨πŸΌ πŸ‘¨πŸΏβ€πŸ€β€πŸ‘¨πŸ½ πŸ‘¨πŸΏβ€πŸ€β€πŸ‘¨πŸΎ πŸ‘¬πŸΏ 🏻 🏼 🏽 🏾 🏿 ';
var b = [...new Set([...a])];
var c = b.join('');
function init() { document.getElementById('result').innerHTML = c; }
</script>
</head><body onload="init()">
<span id="result"></span>
</body>
</html>

JavaScript in HTML code: Random numbers are not evenly distributed

I've got the following problem:
I'm uploading a survey on amazon mturk using Python and the survey is done via HTML and javascript. I show one of three different versions of the survey to participants, which I select by generating a random number via javascript. I store the number in local storage to prevent refreshing the website from resetting it. The problem I find is that more people seem to get versions 1 than version 3. But I cannot recreate the problem for myself when running the code in Tryit Editor online.
Could you please help me understand (and fix) why this happens? The following is the (trimmed) HTML code that I upload. I replaced text and removed fluff.
<HTMLQuestion xmlns="http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2011-11-11/HTMLQuestion.xsd">
<HTMLContent><![CDATA[
<!-- YOUR HTML BEGINS -->
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/>
<script type='text/javascript' src='https://s3.amazonaws.com/mturk-public/externalHIT_v1.js'></script>
<script>
function test(){
document.getElementById('txt-field').value = "1";
}
</script>
</head>
<body>
<form name='mturk_form' method='post' id='mturk_form' action='https://www.mturk.com/mturk/externalSubmit'><input type='hidden' value='' name='assignmentId' id='assignmentId'/>
<span>
<INPUT TYPE="text" NAME="link_click" id='txt-field' value="0" style="display: none">
<div><h3><a href="www.google.com" target="_blank" id='report420' onclick="test()" >link</a></h3>
Instructions</div>
<div><table border="1" style="height: 258px;" width="196"><tbody>Table</tbody></table></div>
</span>
<!--I think the relevant part starts here-->
<script>
document.write("Miscellaneous question");
var i = localStorage.getItem('i') || Math.floor(3*Math.random());
localStorage.setItem('i',i);
if (i==0){
document.write("Version 1");
}
if (i==1){
document.write("Version 2");
}
if (i==2){
document.write("Version 3");
}
document.write("Miscellaneous question");
</script>
<p><input type='submit' id='submitButton' value='Submit' /></p></form>
<script language='Javascript'>turkSetAssignmentID();</script>
</body></html>
<!-- YOUR HTML ENDS -->
]]>
</HTMLContent>
<FrameHeight>600</FrameHeight>
</HTMLQuestion>
The random function Math.floor(3*Math.random()) has uniform distribution, but I don't think that 400 samples are enough so that you can see it in action (as #desoares mentioned).
Testing code:
var count = [0, 0, 0];
var n = 1000000;
document.write('Testing for ' + n + ' samples : ');
for (var i = 0; i < n; i++) {
count[Math.floor(3*Math.random())]++;
}
document.write(JSON.stringify(count));
var count = [0, 0, 0];
var n = 400;
document.write('Testing for ' + n + ' samples : ');
for (var i = 0; i < n; i++) {
count[Math.floor(3*Math.random())]++;
}
document.write(JSON.stringify(count));
Also, if you want to be sure that people from the same computer are not forced to take the same version, you should clear the saved variable localStorage.removeItem('i'); on submit. You may also add an expiration mechanic.

How do I automatically create images in HTML or Javascript?

I am prepared to take hits on this question, because I don't even know how to go about researching this. I did try, don't get me wrong. Maybe someone can tell me what it would even be called. Anyways, I have an .htm file and am passing a variable to it like
Response.Redirect("multiImage.htm?val1=2");
I want to generate val1 many images. so in this example, val1=2, so 2 images generated. I'm not very skilled with html or javascript and this is what I have so far:
<!--When a new camera is added, one needs to change the bound in the for loop in the javascript function in part a.
Then add a new image in part b.-->
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!--********************************Part a**********************************-->
<title>Cameras</title>
<script type="text/javascript" language="JavaScript">
var num = '<%= Request.QueryString("val1") %>';
function refreshIt() {
if (!document.images) return;
for (var i = 1; i <= num; i++) {
document.getElementById("imgcontainer" + i).src = "/Imghandler2.ashx?id=" + i + "&rand=" + Math.random();
}
setTimeout('refreshIt()', 1000);
}
</script>
</head>
<!--********************************Part b**********************************-->
<body onload="setTimeout('refreshIt()',1000)">
<table>
<tr>
That part works, and so does this:
<!-- <td><img id="imgcontainer1" src="/Imghandler2.ashx?id=1" alt="cam image" /></td>
<td><img id="imgcontainer2" src="/Imghandler2.ashx?id=2" alt="cam image" /></td>
</tr>
<tr>
<td><img id="imgcontainer3" src="/Imghandler2.ashx?id=3" alt="cam image" /></td>
<td><img id="imgcontainer4" src="/Imghandler2.ashx?id=4" alt="cam image" /></td>
</tr>
<tr>
<td><img id="imgcontainer5" src="/Imghandler2.ashx?id=5" alt="cam image" /></td>
<td><img id="imgcontainer6" src="/Imghandler2.ashx?id=6" alt="cam image" /></td>-->
But I have commented the above out, because I want to auto generate that. Something like this below. And I know this doesn't work, but hopefully it will give an idea of what I'm trying to do:
<script type="text/javascript" language="JavaScript">
var num = '<%= Request.QueryString("val1") %>';
for (var i = 1; i <= num; i++) {
document.write('<tr>')
document.write('<img id="imgcontainer[i+1]" src="/Imghandler2.ashx?id=[i+1]" alt="cam image" />')
document.write('</tr>')
}
</script>
</tr>
</table>
</body>
</html>
Like I said, I don't even know how I would go about researching this. I did try, but didn't find what I needed. Is this even possible?
After more research I found out how to do this. Here is my full html code:
<!--This .htm file creates an img for the image to be displayed. The number img's created is equal to the number
of cameras selected in "Main.aspx"-->
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Cameras</title>
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<!--*************************beginning of javascript code******************************-->
<script type="text/javascript" language="JavaScript">
// Function gets the parameter values in the url string.
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
// Function programmatically creates a new img for each camera selected in Main.aspx.
function add() {
for (var i = 1; i <= getParameterByName('val1'); i++) {
var element = document.createElement("img");
element.setAttribute("id", "imgcontainer" + i.toString());
element.setAttribute("src", "/Imghandler2.ashx?id=" + i.toString());
element.setAttribute("alt", "cam image");
document.getElementById("table1").appendChild(element);
}
}
// Function updates each image in each img
function refreshIt() {
if (!document.images) return;
for (var i = 1; i <= getParameterByName('val1'); i++) {
document.getElementById("imgcontainer" + i).src = "/Imghandler2.ashx?id=" + i + "&rand=" + Math.random();
}
setTimeout('refreshIt()', 1000);
}
</script>
<!--*************************end of javascript code******************************-->
</head>
<body onload="add(); setTimeout('refreshIt()',1000);">
<table id="table1">
</table>
</body>
</html>

Form button keeps showing results in new window

Very new to html and javascript here. I get the following form up and it calculates correctly but the result shows up in a new page. I'd like it to stay in the same page. Not sure what I did wrong here. Also, is there any way to shorten the function? Seems like a lot of work to do a simple calculation. Any help would be great.
<html>
<head>
<title>Help!</help>
<script type="text/javascript">
function add(x,y){
var x = document.add1.add2.value;
var y = document.add1.add3.value;
var x = Number(x);
var y = Number(y);
var z = x+y;
return (z);
}
</script>
</head>
<body>
<h3>Help me stack overflow you're my only hope!</h3>
<form name="add1">
Input first number to add: <input type="number" name="add2">
2nd number: <input type="number" name="add3">
<input type="button" value="Result"
onclick = "document.write('The total is: ' + add() + '.');" />
</body>
</html>
Dont' use document.write to display data, it overwrites entire document. You don't want that. It's better to create new function which would render result into some other element:
<input type="button" value="Result" onclick="showResult('The total is: ' + add() + '.');" />
and the showResult function can be for example:
function showResult(result) {
document.getElementById('result').innerHTML = result;
}
HTML:
<div id="result"></div>
Demo: http://jsfiddle.net/7ujzn35c/
Here are also a couple of general improvements you can make your code:
move string manupulations to showResult completely:
<input type="button" value="Result" onclick="showResult()" />
http://jsfiddle.net/7ujzn35c/1/
call add from inside showResults
onclick="showResult(this.form.add2.value, this.form.add3.value)"
http://jsfiddle.net/7ujzn35c/2/
<title>Help!</help>
First of all, This should be <title> Help! </title>
Secondly, document.write function actually starts writing the entire page anew.
You should either replace onclick = "document.write('The total is: ' + add() + '.');" with
onclick = "alert('The total is: ' + add() + '.');"
Better still, you could create a div element like so
<title> Help! </title>
<script>
.....
</script>
</header>
<body>
<div id = 'output'> </div> ...
then
`onclick = "document.getElementById("output").innerHTML = 'The total is: ' + add() + '.';"
And don't give up. Hope this helps you

javascript multiple loops

I am trying to get the sum of a list of words displayed in an HTML browser.
If each word is assigned a number i.e
a is 1,
b is 2
and so on upto z is 26, then the sum of apple should be 50. I want them to be displayed in browser like below:
apple
carrot
money
50
75
72
but I am not able to get the loop to work correctly.
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" rev="stylesheet" href="script.css" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function newSquare(){
for(var j=0; j<10; j++){
calcAlpha(j);
}
}
function newDisplay(){
for(var k=0; k<10; k++){
calcAlpha(k);
}
}
function calcAlpha() {
var word = document.getElementById("square + j").childNodes[0].data;
var sum = 0;
for(var i=word.length-1; i>=0; i--) {
sum += (word.charCodeAt(i) - 96);
}
document.getElementById("display + k").innerHTML=sum
}
</script>
</head>
<body>
<h1>Calculate sum of words</h1>
<table>
<tr><td id="square1">apple</td></tr>
<tr><td id="square2">carrot</td></tr>
<tr><td id="square3">money</td></tr>
<tr><td id="square4">game</td></tr>
</table>
<table>
<tr><td id="display1"> </td></tr>
<tr><td id="display2"> </td></tr>
<tr><td id="display3"> </td></tr>
<tr><td id="display4"> </td></tr>
</table>
<div id="display"></div>
<button onclick="calcAlpha()">calculate</button>
</body>
</html>
Can someone can sort this for me? I am still a beginner at Javascript, and I dont understand how to put i,j, and k in loops.
Thanks.
Here's a complete answer:
There are three main problems with the code. First, i, j, and k are var's with specific integer values in this example. "square + j" is just a string that does not have the desired values (i.e. square1, square2, etc.). As Michael has suggested, you should put "square" + j.
The second issue is that the only function to run in your webpage is calcAlpha(), which you call in the onclick event of the button element. Within calcaAlpha() you never call newSquare() or newDisplay(), so they never execute.
The third issue is the namespace, or scope of your javascript variables. Within calcAlpha() you cannot access the variables j or k because they are declared in external functions that don't encapsulate the calcAlpha() function. However, you can access the variable i because it is declared in calcAlpha().
The solution to your problem would be to remove newDisplay() and newSquare() and change calcAlpha() to something like this:
function calcAlpha() {
for (var j = 1; j <= 4; j++) {
var word = document.getElementById("square" + j).childNodes[0].data;
var sum = 0;
for(var i=word.length-1; i>=0; i--) {
sum += (word.charCodeAt(i) - 96);
}
document.getElementById("display" + j).innerHTML=sum
}
}
This is basically the combined code for newSquare() and newDisplay() which is put into calcAlpha() and fixed for the other issues described above. Notice that the variable k is unnecessary because you want to put the numeric sum of squareN into displayN, so you can use a single variable, j.
I'm not sure what you want to do with those functions, but try this:
function run() {
// reads, calculates and prints all words
for (var i=1; i<=4; i++) {
var word = document.getElementById("square"+i).childNodes[0].data;
var result = calcAlpha(word);
document.getElementById("display"+i).childNodes[0].data = result;
}
}
function calcAlpha(text) {
text = text.toLowerCase();
var sum = 0;
for (var i=text.length-1; i>=0; i--) {
sum += text.charCodeAt(i) - 96;
}
return sum;
}
And call the run function from the button.
One thing I saw that you did incorrectly right away was getting the element by id. You were including the looping variable as a string instead of an int. Here is my solution:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function calcAlpha()
{
for(j =1; j<=4; j++)
{
var word = document.getElementById("square" + j).innerHTML;
var sum = 0;
for(var i=word.length-1; i>=0; i--)
{
sum += (word.charCodeAt(i) - 96);
}
document.getElementById("display" + j).innerHTML=sum
}
}
</script>
</head>
<body>
<h1>Calculate sum of words</h1>
<table>
<tr><td id="square1">apple</td></tr>
<tr><td id="square2">carrot</td></tr>
<tr><td id="square3">money</td></tr>
<tr><td id="square4">game</td></tr>
</table>
<table>
<tr><td id="display1"> </td></tr>
<tr><td id="display2"> </td></tr>
<tr><td id="display3"> </td></tr>
<tr><td id="display4"> </td></tr>
</table>
<div id="display"></div>
<button onclick="calcAlpha()">calculate</button>
</body>
</html>
The first problem, like Michael said, is this:
document.getElementById("square + j")
// and
document.getElementById("display + k")
This will look for the element whose id exactly matches "square + j" or "display + k". To concatenate the value of a variable to a string, use "square" + j and "display" + k.
The second problem is that in the context of calcAlpha, the variables j and k are undefined. You can fix this by either making them accessible to calcAlpha (by defining them outside the scope of function calcAlpha) or by passing j (or k) as a parameter. You're already doing the first part of that (actually passing it along). All you need now is to use it in the declaration of calcAlpha, like so:
function calcAlpha(index) {
var word = document.getElementById("square" + index).childNodes[0].data;
// [...]
}
The variable index will now contain the value of the j or k you passed along.
One other thing: you're calling calcAlpha both from the other functions and from the <button>'s onclick. That's probably not what you want to do. Have a look at Bergi's answer, his/her solution should solve your problem.

Categories

Resources