JavaScript If Else errors - javascript

So I have this little problem with my if else structure. When I put in a correct star for example "Vega", the costellation shows me that it is false ("Error") while it needs to show me "Lyra".
My code is below:
var stars = ["Polaris", "Aldebaran", "Deneb", "Vega", "Altair", "Dubhe", "Regulus"];
var costellations = ["Ursu Minor", "Taurus", "Cygnus", "Lyra", "Aquila", "Ursa Major","Leo"];
function Arrays() {
for (n = 0; n < 7; ++n) {
if (test.inputStars.value == stars[n]) {
test.inputCostellations.value = costellations[n];
}else{
test.inputCostellations.value = "Error";
}
}
}
<!DOCTYPE html>
<html>
<head>
<title> Array structures</title>
</head>
<body>
<form name = "test">
<input type = "text" name = "inputStars">
<input type = "button" onclick ="Arrays()" value = "Find costellation">
<input type = "text" name = "inputCostellations">
</form>
</body>
</html>

The problem is, when the for loop is running, the test.inputConstellations.value will be overridden, even if previously the program found a match. The solution is the break:
if(test.inputStars.value==stars[n]){
test.inputConstellations.value=constellations[n]
break
}else{
test.inputCostellations.value = "Error"
}
var stars = ["Polaris", "Aldebaran", "Deneb", "Vega", "Altair", "Dubhe", "Regulus"];
var costellations = ["Ursu Minor", "Taurus", "Cygnus", "Lyra", "Aquila", "Ursa Major","Leo"];
function Arrays() {
for (n = 0; n < 7; ++n) {
if (test.inputStars.value == stars[n]) {
test.inputCostellations.value = costellations[n];
break
}else{
test.inputCostellations.value = "Error";
}
}
}
<!DOCTYPE html>
<html>
<head>
<title> Array structures</title>
</head>
<body>
<form name = "test">
<input type = "text" name = "inputStars">
<input type = "button" onclick ="Arrays()" value = "Find costellation">
<input type = "text" name = "inputCostellations">
</form>
</body>
</html>

You can set a default value for variable and overwrite when true:
var stars = ["Polaris", "Aldebaran", "Deneb", "Vega", "Altair", "Dubhe", "Regulus"];
var costellations = ["Ursu Minor", "Taurus", "Cygnus", "Lyra", "Aquila", "Ursa Major","Leo"];
function Arrays() {
test.inputCostellations.value = "Error";
for (n = 0; n < 7; ++n) {
if (test.inputStars.value == stars[n]) {
test.inputCostellations.value = costellations[n];
}
}
}
And use a break:
var stars = ["Polaris", "Aldebaran", "Deneb", "Vega", "Altair", "Dubhe", "Regulus"];
var costellations = ["Ursu Minor", "Taurus", "Cygnus", "Lyra", "Aquila", "Ursa Major","Leo"];
function Arrays() {
test.inputCostellations.value = "Error";
for (n = 0; n < 7; ++n) {
if (test.inputStars.value == stars[n]) {
test.inputCostellations.value = costellations[n];
break;
}
}
}

Related

HTML --- Javascript/JSON

okay here is the question -- .. i tried it but my js isn't working and idk where i am wrong here is the question
THE PROBLEM IS AFTER THE JS EXECUTED IT DOESN'T RUN ... LIKE IDK WHERE THE PROBLEM IS ; I KNOW IT LOADS BUT IT DOES'NT WORK
<html>
<head>
<script src="q2.js" type="text/javascript"> </script>
</head>
<div > Input 1 <input type="text" id ="input1"></div>
<div> Input 2 <input type="text" id ="input2"> </div>
<div> Result <div id="result"> </div></div>
<button onclick= "compute()">Compute</button>
</body>
</html>
the js is here
function compute(){
var n = (document.getElementById("input1").value;
var m = document.getElementById("input2").value;
var i,j;
if (Number(n)){
}
else {
alert("Error! Please put a valid Number - on input 1 ");
}
if (Number(m)){
}
else {
alert("Error! Please put a valid Number - on input 2 ");
}
for(i = 0; i < n; i++){
for(j = 0; j < m; j++){
result.innerHTML += "X";
if(j == (m-1)){
result.innerHTML += "<br />";
}
}
}
}
result.innerHTML += "X";
You forgot to set the variable result:
var result = document.getElementById("result");
And there is a loneley ( in var n = (document.getElementById("input1").value; wich will through syntax error
And you might want to clear the content of your "result"-container when calling the function again: result.innerHMLT = ''
function compute() {
var n = document.getElementById("input1").value;
var m = document.getElementById("input2").value;
var result = document.getElementById("result");
result.innerHMLT = ''
var i, j;
if (Number(n)) {} else {
alert("Error! Please put a valid Number - on input 1 ");
}
if (Number(m)) {} else {
alert("Error! Please put a valid Number - on input 2 ");
}
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
result.innerHTML += "X";
if (j == (m - 1)) {
result.innerHTML += "<br />";
}
}
}
}
<div>Input 1
<input type="text" id="input1">
</div>
<div>Input 2
<input type="text" id="input2">
</div>
<div>Result
<div id="result"></div>
</div>
<button onclick="compute()">Compute</button>

Javascript flow control glitch

UPDATE: SOLVED! line 116 (ERROR3) had to be changed from 'parseInst(rom[i]); ' to 'rom[i]; '.
I'm working on an assembly simulator in Javascript. For some reason the JUMP instruction messes up the register contents. The following program (can be copy-pasted) increments register 'A' (0-->1) then jumps to instruction 0. Instead of '1', the register's content becomes a value over 5000. What am I doing wrong? UPDATE: added three errors caught by the debugger ("Uncaught RangeError: Maximum call stack size exceeded").
var regA = 0;
var regB = 0;
var accu = 0;
var rom = [];
var instCount = 0;
var flag1 = 0;
var stopState = 0;
function eval() {
var inst = document.getElementById("text_f").value;
parseInst(inst);
};
function parseInst(instString) {
if (instString.includes("LDA")) { //ERROR1
var strSplitA = instString.split(":");
regA = parseInt(strSplitA[1]);
document.getElementById("regA").innerHTML = regA;
instCount++;
document.getElementById("demo").innerHTML = "load register A: " + strSplitA[1]+"type of: "+typeof regA;
} else if (instString.includes("LDB")) {
var strSplitB = instString.split(":");
document.getElementById("demo").innerHTML = "load register B: " + strSplitB[1];
regB = parseInt(strSplitB[1]);
document.getElementById("regB").innerHTML = regB;
instCount++;
} else if (instString == "ADD") {
accu = regA + regB;
document.getElementById("demo").innerHTML = "add " + regA + "+" + regB + "=" + accu;
document.getElementById("accu").innerHTML = accu;
instCount++;
} else if (instString.includes("JMP")) {
var jumpTo = instString.split(":");
instCount = parseInt(jumpTo[1]);
document.getElementById("demo").innerHTML = "jump to: " + instCount+" typeof: "+typeof instCount;
document.getElementById("count").innerHTML = instCount;
runStop(stopState,parseInt(jumpTo[1])); //ERROR2
} else if (instString == "CMP") {
if (regA === regB) {
flag1 = 1;
instCount++;
document.getElementById("flag1").innerHTML = 1;
document.getElementById("demo").innerHTML = "flag1 set to 1";
} else {
flag1 = 0;
instCount++;
document.getElementById("flag1").innerHTML = 0;
document.getElementById("demo").innerHTML = "flag1 set to 0";
};
} else if (instString.includes("INC")) {
var incRegister = instString.split(":");
switch (incRegister[1]) {
case "A":
regA++;
document.getElementById("demo").innerHTML = "case A";
document.getElementById("regA").innerHTML = regA;
instCount++;
break;
case "B":
regB++;
document.getElementById("demo").innerHTML = "case B";
document.getElementById("regB").innerHTML = regB;
instCount++;
break;
default:
document.getElementById("demo").innerHTML = "error: register name";
break;
}
} else {
document.getElementById("demo").innerHTML = "error: no instruction";
};
};
function saveToRom() {
var romString = document.getElementById("text_f").value;
rom = romString.split(",");
document.getElementById("rom").innerHTML = rom;
document.getElementById("demo").innerHTML = "#debug:save to rom";
reset();
};
function step() {
parseInst(rom[instCount]);
document.getElementById("count").innerHTML = instCount-1;
};
function run() {
stopState = 0;
document.getElementById("demo").innerHTML = "run";
runStop(stopState,instCount);
};
function stop(){
stopState = 1;
document.getElementById("demo").innerHTML = "stop";
runStop(stopState,instCount);
};
function runStop(stopSt,instructionCount){
if(stopSt == 0){
for(var i=instructionCount;i<rom.length;i++){
parseInst(rom[i]); //ERROR3
document.getElementById("demo").innerHTML = "#runStop(): stopState: "+stopState+" for loop length: " + rom.length;
}
} else {
document.getElementById("demo").innerHTML = "#runStop(): stopState: "+stopState;
};
};
function reset() {
document.getElementById("demo").innerHTML = "debug: reset";
regA = 0;
regB = 0;
accu = 0;
flag1 = 0;
instCount = 0;
document.getElementById("regA").innerHTML = regA;
document.getElementById("regB").innerHTML = regB;
document.getElementById("accu").innerHTML = accu;
document.getElementById("count").innerHTML = instCount;
document.getElementById("flag1").innerHTML = flag1;
};
The full source code with HTML on Github.
I appreciate your help in advance! EDIT: The html code
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>COMPU</title>
<script type='text/javascript' src='comp3.1.js'></script>
<link rel="stylesheet" type="text/css" href="stylesheet_comp.css">
</head>
<body>
<input type="text" id="text_f" value=" " autofocus>
<br><br>
<div class="nav">
<button onclick="eval()">EXEC</button>
<button onclick="saveToRom()">SAVE</button>
<button onclick="reset()">RST</button>
<button onclick="step()">STEP</button>
<button onclick="run()">RUN</button>
<button id="stop" value=0 onclick="stop()">STOP</button>
</div>
<br>
<div class="displays">
DEBUG:
<p id="demo">*debugging messages*</p>
REG A:
<p id="regA">0</p>
REG B:
<p id="regB">0</p>
ACCU:
<p id="accu">0</p>
<br> ROM:
<p id="rom"></p>
INS COUNT:
<p id="count">0</p>
FLAG1:
<p id="flag1">0</p>
<!--
DEBUG2:
<p id="dbg2"></p>
-->
</div>
INSTRUCTIONS:
<ol>
<li>ADD</li>
</ol>
</body>
</html>
UPDATE: SOLVED! line 116 (ERROR3) had to be changed from 'parseInst(rom[i]); ' to 'rom[i]; '.

output as undefined/NAN

Would anyone clerify why my program is outputting undefined or NAN? I know for sure that my random number generator is working. Also, I'm trying to sum up all of the "score" value when the number generator has generated the value 10 times. Thanks for the help
<HTML>
<!Foundation Page for building our Javascript programs>
<HEAD>
<TITLE>The Foundation Page </TITLE>
<SCRIPT LANGUAGE = "JavaScript">
function main()
{
randomnumber()
totalscore()
}
function randomnumber()
{
var randomnumber;
randomnumber = Math.random()*3;
return(Math.floor(randomnumber+0.5));
}
function totalscore()
{
var n;
var score;
var number;
number = randomnumber()
for (n=0;n<11; n=n+1)
{
if (number==0)
{
score =score+0
}
if (number==2)
{
score =score+2
}
if (number==3)
{
score =score+3
}
document.write(score)
}
}
</SCRIPT>
<HEAD>
<BODY>
<BODY BGCOLOUR = "WHITE">
<H2>The Foundation Page </H2>
<HR>
<SCRIPT LANGUAGE = "Javascript"> main() </SCRIPT>
<INPUT NAME = "dobutton" TYPE = "button" value = "Start game" on Click = "game()">
<INPUT NAME = "dobutton" TYPE = "button" value = "Leaderboard" on Click = "leader()">
</BODY>
</HTML>
Because score variable is undefined. You should initialize it with a number for instance: var score = 0;
Variable score is declared in your totalscore function but never initialised. Adding anything to undefined gives NaN, which is what your function writes to the page.
You need to initialize your score variable with 0. Until you don't, it's value is undefined and when you do math operations on an undefined object, you wil get a NaN error. I have also formatted your code a bit.
<HTML>
<!Foundation Page for building our Javascript programs>
<HEAD>
<TITLE>The Foundation Page </TITLE>
<SCRIPT LANGUAGE = "JavaScript">
function main()
{
randomnumber()
totalscore()
}
function randomnumber()
{
var randomnumber;
randomnumber = Math.random()*3;
return(Math.floor(randomnumber+0.5));
}
function totalscore()
{
var n;
var score = 0;
var number = randomnumber();
for (n = 0 ; n < 11 ; ++n)
{
if (number == 0){
score += 0;
}
else if (number == 2)
{
score += 2;
}
else if (number == 3)
{
score += 3;
}
document.write(score)
}
}
</SCRIPT>
<HEAD>
<BODY>
<BODY BGCOLOUR = "WHITE">
<H2>The Foundation Page </H2>
<HR>
<SCRIPT LANGUAGE = "Javascript"> main() </SCRIPT>
<INPUT NAME = "dobutton" TYPE = "button" value = "Start game" on Click = "game()">
<INPUT NAME = "dobutton" TYPE = "button" value = "Leaderboard" on Click = "leader()">
</BODY>
</HTML>
EDIT: If I understand your comment correctly, you should be doing something like this
function totalscore()
{
var n;
var score = 0;
for (n = 0 ; n < 10 ; ++n)
{
score += randomnumber();
document.write(score)
}
var grandTotal = score;
}

Push value to array onclick and loop to add array values. Javascript

So i am pretty new at this and want to be able to add a dollar to the "deposit" text box every time I click the button. I'm going to have to do this with a quarter, dime, and nickel, button as well. This is what I have so far.
<input type="button" value="Dollar" id="dollar" />
$<input type="text" id="deposit" />
And the javascript is:
var $ = function (id) { return document.getElementById(id); }
var item = [];
var total = 0;
for (i=0; i < item.length; i++){
total += item[i];
$("deposit").value = total;
}
$("dollar").onclick = item.push(1);
Whatever help you can give is much appreciated!
Don't you mean
Live Demo
var $ = function (id) { return document.getElementById(id); }
var add = function(fld,val) {
return (parseFloat(fld.value)+val).toFixed(2);
}
window.onload=function() {
$("dollar").onclick=function() {
$("deposit").value = add($("deposit"),1);
}
$("dime").onclick=function() {
$("deposit").value = add($("deposit"),.1);
}
$("nickel").onclick=function() {
$("deposit").value = add($("deposit"),.05);
}
$("refund").onclick = function() {
$("deposit").value = "0.00";
}
}
Try this:
HTML
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#1.9.1" data-semver="1.9.1" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<input type="button" value="Dollar" id="dollar" />
$ <input type="text" id="deposit" />
</body>
</html>
JavaScript:
$(function() {
var item = [];
$("#dollar").click(function() {
item.push(1);
var total = 0;
for (var i = 0; i < item.length; i++) {
total += item[i];
$("#deposit").val(total);
}
});
});
Plunker example

Sorting table using javascript sort()

I am trying to sort a table. I've seen several jQuery and JavaScript solutions which do this through various means, however, haven't seen any that use JavaScript's native sort() method. Maybe I am wrong, but it seems to me that using sort() would be faster.
Below is my attempt, however, I am definitely missing something. Is what I am trying to do feasible, or should I abandon it? Ideally, I would like to stay away from innerHTML and jQuery. Thanks
var index = 0; //Index to sort on.
var a = document.getElementById('myTable').rows;
//sort() doesn't work on collection
var b = [];
for (var i = a.length >>> 0; i--;) {
b[i] = a[i];
}
var x_td, y_td;
b.sort(function(x, y) {
//Having to use getElementsByTagName is probably wrong
x_td = x.getElementsByTagName('td')[index].data;
y_td = y.getElementsByTagName('td')[index].data;
return x_td == y_td ? 0 : (x_td < y_td ? -1 : 1);
});
A td element doesn't have a .data property.
If you wanted the text content of the element, and if there's only a single text node, then use .firstChild before .data.
Then when that is done, you need to append the elements to the DOM. Sorting a JavaScript Array of elements doesn't have any impact on the DOM.
Also, instead of getElementsByTagName("td"), you can just use .cells.
b.sort(function(rowx, rowy) {
x_td = rowx.cells[index].firstChild.data;
y_td = rowy.cells[index].firstChild.data;
return x_td == y_td ? 0 : (x_td < y_td ? -1 : 1);
});
var parent = b[0].parentNode;
b.forEach(function(row) {
parent.appendChild(row);
});
If the content that you're comparing is numeric, you should convert the strings to numbers.
If they are text strings, then you should use .localeCompare().
return x_td.localeCompare(y_td);
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>All Sorting Techniques</title>
<script type="text/javascript">
var a = [21,5,7,318,3,4,9,1,34,67,33,109,23,156,283];
function bubbleSort(a)
{
var change;
do {
change = false;
for (var i=0; i < a.length-1; i++) {
if (a[i] > a[i+1]) {
var temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
change = true;
}
}
} while (change);
document.getElementById("bublsrt").innerHTML = "Bubble Sort Result is: "+a;
}
var b = [1,3,4,5,7,9,21,23,33,34,67,109,156,283,318];
function binarySearch(b, elem){
var left = 0;
var right = b.length - 1;
while (left <= right){
var mid = parseInt((left + right)/2);
if (b[mid] == elem)
return mid;
else if (b[mid] < elem)
left = mid + 1;
else
right = mid - 1;
}
return b.length;
}
function searchbinary(){
var x = document.getElementById("binarysearchtb").value;
var element= binarySearch(b,x);
if(element==b.length)
{
alert("no. not found");
}
else
{
alert("Element is at the index number: "+ element);
}
}
function quicksort(a)
{
if (a.length == 0)
return [];
var left = new Array();
var right = new Array();
var pivot = a[0];
for (var i = 1; i < a.length; i++) {
if (a[i] < pivot) {
left.push(a[i]);
} else {
right.push(a[i]);
}
}
return quicksort(left).concat(pivot, quicksort(right));
}
function quicksortresult()
{
quicksort(a);
document.getElementById("qcksrt").innerHTML = "Quick Sort Result is: "+quicksort(a);
}
function numeric(evt){
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
var regex = /[0-9]|\./;
if (!regex.test(key)) {
theEvent.returnValue = false;
if (theEvent.preventDefault)
theEvent.preventDefault();
}
}
function insertionsorting(a)
{
var len = a.length;
var temp;
var i;
var j;
for (i=0; i < len; i++) {
temp = a[i];
for (j=i-1; j > -1 && a[j] > temp; j--) {
a[j+1] = a[j];
}
a[j+1] = temp;
}
document.getElementById("insrtsrt").innerHTML = "Insertion Sort Result is: "+a;
}
function hiddendiv()
{
document.getElementById("binarytbdiv").style.display = "none";
document.getElementById("Insertnotbdiv").style.display = "none";
}
function binarydivshow()
{
document.getElementById("binarytbdiv").style.display = "block";
}
function insertnodivshow()
{
document.getElementById("Insertnotbdiv").style.display = "block";
}
function insertno(a)
{
var extrano = document.getElementById("Insertnotb").value;
var b= a.push(extrano);
var change;
do {
change = false;
for (var i=0; i < a.length-1; i++) {
if (a[i] > a[i+1]) {
var temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
change = true;
}
}
} while (change);
document.getElementById("insrtnosearch").innerHTML = "Sorted List is: "+a;
alert("Index of "+extrano +" is " +a.indexOf(extrano));
}
</script>
</head>
<body onload="hiddendiv()">
<h1 align="center">All Type Of Sorting</h1>
<p align="center">Your Array is : 21,5,7,318,3,4,9,1,34,67,33,109,23,156,283</p>
<div id="main_div" align="center">
<div id="bubblesort">
<input type="button" id="bubblesortbutton" onclick="bubbleSort(a)" value="Bubble Sort">
<p id="bublsrt"></p>
</div><br>
<div id="quicksort">
<input type="button" id="quicksortbutton" onclick="quicksortresult()" value="Quick Sort">
<p id="qcksrt"></p>
</div><br>
<div id="insertionsort">
<input type="button" id="insertionsortbutton" onclick="insertionsorting(a)" value="Insertion Sort">
<p id="insrtsrt"></p>
</div><br>
<div id="binarysearch">
<input type="button" id="binarysearchbutton" onclick="binarydivshow();" value="Binary Search">
<div id="binarytbdiv">
<input type="text" id="binarysearchtb" placeholder="Enter a Number" onkeypress="numeric(event)"><br>
<input type="button" id="binarysearchtbbutton" value="Submit" onclick="searchbinary()">
<p id="binarysrch">Sorted List is : 1,3,4,5,7,9,21,23,33,34,67,109,156,283,318</p>
</div>
</div><br>
<div id="Insertno">
<input type="button" id="insertno" onclick="insertnodivshow()" value="Insert A Number">
<div id="Insertnotbdiv">
<input type="text" id="Insertnotb" placeholder="Enter a Number" onkeypress="numeric(event);"><br>
<input type="button" id="Insertnotbbutton" value="Submit" onclick="insertno(a)">
<p id="insrtnosearch"></p>
</div>
</div>
</div>
</body>
</html>

Categories

Resources