Compare and Output 2 strings in JavaScript - javascript

I am new to JavaScript, and I'm trying to make a web page where if I have the same open and closing hours for 5 days a week, it will output them on the same line. For example, the hours for Monday - Friday are the same in my example so it would print out:
Monday - Friday: 6:00AM - 2:00PM
Saturday 8:00AM - 1:00PM
Sunday Closed (Without the hyphen)
When I run this in my browser, I get a blank page. Here is my code:
<!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>
<script>
var MondayOpen = "6:00AM - ";
var MondayClose = "2:00PM";
var TuesdayOpen = "6:00AM - ";
var TuesdayClose = "2:00PM";
var WednesdayOpen = "6:00AM - ";
var WednesdayClose = "2:00PM";
var ThursdayOpen = "6:00AM - ";
var ThursdayClose = "2:00PM";
var FridayOpen = "6:00AM - ";
var FridayClose = "2:00PM";
var SaturdayOpen = "8:00AM - ";
var SaturdayClose = "1:00PM";
var SundayOpen = "Closed";
var SundayClose = "";
var dateArray = new Array(MondayOpen, MondayClose, TuesdayOpen, TuesdayClose, WednesdayOpen, WednesdayClose, ThursdayOpen, ThursdayClose,FridayOpen, FridayClose, SaturdayOpen, SaturdayClose, SundayOpen, SundayClose);
function outputDate(){
for(int i = 0; i<dateArray.length; i++){
var current;
//Puts Open and Close time into 1 string
dateArray[i] + dateArray[i+1] = current;
//Compare the two strings
if(current.substring(0,15) == current.substring(0,15) +2)
}
$("#hours").html(<b> current <b/>);
}
var getHours = document.getElementById('hours').innterHTML = current;
}
</script>
<div id= "hours" style="font-size:10px; color:#fff;">
</div>
What am I missing here? Any help would be appreciated.

There are several mistakes here. Just to name a few:
You put int instead of var here:
for(var i = 0; i<dateArray.length; i++){
You put String instead of var here:
var curr;
You're assigning a variable to an expression? Did you mean to do it the other way around?
//Puts Open and Close time into 1 string
curr = dateArray[i] + dateArray[i+1];
You have a closing brace after your if statement...
//Compare the two strings
if(current.substring(0,15) == current.substring(0,15) +2)
{
You type innterHTML instead of innerHTML and try to do multiple assignments:
var getHours = current;
document.getElementById('hours').innerHTML = current;
You forget to enclose this in quotes:
$("#hours").html("<b> current <b/>");
EVEN after fixing all these syntax errors I get a blank page. Consider rewriting it from scratch.

In Javascript you don't need to declare String theString = "This is a string".
Just write var stringName = "This is my string."

You might want to take a step back and master JavaScript and HTML. There are many free resources available. Just to be brief, why not try Code Academy or W3 schools. That being said, here's enough of a fix to display your variables.
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
</head>
<body>
<div id="hours"></div>
</body>
<script type="text/javascript">
var MondayOpen = "6:00AM - ";
var MondayClose = "2:00PM";
var TuesdayOpen = "6:00AM - ";
var TuesdayClose = "2:00PM";
var WednesdayOpen = "6:00AM - ";
var WednesdayClose = "2:00PM";
var ThursdayOpen = "6:00AM - ";
var ThursdayClose = "2:00PM";
var FridayOpen = "6:00AM - ";
var FridayClose = "2:00PM";
var SaturdayOpen = "8:00AM - ";
var SaturdayClose = "1:00PM";
var SundayOpen = "Closed";
var SundayClose = "";
var dateArray = new Array(MondayOpen, MondayClose, TuesdayOpen, TuesdayClose, WednesdayOpen, WednesdayClose, ThursdayOpen, ThursdayClose,FridayOpen, FridayClose, SaturdayOpen, SaturdayClose, SundayOpen, SundayClose);
function outputDate(){
var printOutResults;
for(i = 0; i<dateArray.length; i++) {
var current;
//Puts Open and Close time into 1 string
current = dateArray[i] + dateArray[i+1];
printOutResults += current;
//Compare the two
if(current.substring(0,15) == current.substring(0,15) +2){
$("#hours").html(current);
}
}
$("#hours").html(printOutResults);
}
outputDate();
</script>

Related

Array sort build in function

I was wondering what's wrong with my program. Am i having a syntax error or am i missing something in my build in array sort?. I'm pretty sure the problem lies within the "for" loop but i cant seem to find it. Some suggestion or help would be great.
<HTML>
<!Foundation Page for building our Javascript programs>
<HEAD>
<TITLE>The Foundation Page </TITLE>
<SCRIPT LANGUAGE = "JavaScript">
function leaderboard()
{
var temp1;
var temp2;
var temp3;
var temp4;
var temp5;
temp1 = 10
temp2 = 20
temp3 = 30
temp4 = 40
temp5 = 50
var leader = new Array(5);
leader[0] = temp1;
leader[1] = temp2;
leader[2] = temp3;
leader[3] = temp4;
leader[4] = temp5;
leader.sort(function(a,b){return b-a});
var myContent = '';
for (var d=0;d<5;d++)
{
myContent += "score: " + leader[d] + "<BR>";
}
document.getElementById("leaderboard").innerHTML = myContent;
}
</SCRIPT>
<HEAD>
<BODY>
<BODY BGCOLOUR = "WHITE">
<H2>The Foundation Page </H2>
<HR>
<SCRIPT LANGUAGE = "Javascript"> leaderboard() </SCRIPT>
</BODY>
</HTML>
You are trying to write the o/p to an element with id leaderboard which is not present in the page. Which is giving an error Uncaught TypeError: Cannot set property 'innerHTML' of null - it is not a syntax error.
So just create an element with the id leaderboard as shown below
<HTML>
<!Foundation Page for building our Javascript programs>
<HEAD>
<TITLE>The Foundation Page </TITLE>
<SCRIPT LANGUAGE = "JavaScript">
function leaderboard()
{
var temp1;
var temp2;
var temp3;
var temp4;
var temp5;
temp1 = 10
temp2 = 20
temp3 = 30
temp4 = 40
temp5 = 50
var leader = new Array(5);
leader[0] = temp1;
leader[1] = temp2;
leader[2] = temp3;
leader[3] = temp4;
leader[4] = temp5;
leader.sort(function(a,b){return b-a});
var myContent = '';
for (var d=0;d<5;d++)
{
myContent += "score: " + leader[d] + "<BR>";
}
document.getElementById("leaderboard").innerHTML = myContent;
}
</SCRIPT>
<HEAD>
<BODY>
<BODY BGCOLOUR = "WHITE">
<H2>The Foundation Page </H2>
<HR>
<div id="leaderboard"></div>
<SCRIPT LANGUAGE = "Javascript"> leaderboard() </SCRIPT>
</BODY>
</HTML>
Demo: Fiddle

Javascript math not working, better way to perform operations?

I included the javascript links above the <head>
I'm wondering about doing this in like one line.
I try this in a basic .html file and nothing shows up, no alert.
I'm probably missing something trivial.
Wait, probably just have to put the dollar signs haha
<!DOCTYPE HTML>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script language="JavaScript" type="text/javascript"></script>
<head>
<style>
</style>
</head>
<body>
<script>
function compute(){
var h = 1595;
var k = 77;
var r = 309;
var rSquared = Math.pow(r,2);
var x = 686;
var group = x - h;
var groupSquared = Math.pow(group,2);
var toBeSquareRoot = rSquared - groupSquared;
var y_neg = 77 + Math.sqrt(toBeSquareRoot);
var y_pos = 77 - Math.sqrt(toBeSquareRoot);
alert(y_pos);
alert(y_neg);
alert(hey);
}
compute();
</script>
</body>
Just a few syntax errors. Ditch the single quotes on the alerts. Also, you were missing the Math. before the pow() method call.
<script>
function compute(){
var h = 1595;
var k = 77;
var r = 309;
var rSquared = Math.pow(r,2);
var x = 686;
var group = x - h;
var groupSquared = Math.pow(group,2);
var toBeSquareRoot = rSquared - groupSquared;
var y_neg = 77 + Math.sqrt(toBeSquareRoot);
var y_pos = 77 - Math.sqrt(toBeSquareRoot);
alert(y_pos);
alert(y_neg);
alert('hey');
}
compute();
</script>
Your code is returning NaN. This is probably due to a negative number being passed into the .sqrt() method. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sqrt

How to display Javascript variable in specific HTML div?

I'm very new to using Javascript and I want to display this variable on my homepage for my portfolio
<html lang="en">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
var curDate = new Date();
var curYear = curDate.getUTCFullYear(),
curMonth = curDate.getUTCMonth(),
curDay = curDate.getUTCDate();
var myYear = 1996,
myMonth = 10,
myDay = 22;
var myAge = curYear % myYear;
if (curMonth < myMonth && curDay < myDay || curMonth < myMonth && curDay === myDay || curMonth == myMonth && curDay < myDay) {
myAge -= 1;
}
var myAgeDiv = document.getElementById('my-age');
myAgeDiv.textContent = myAge;
$('#my-age').text(myAge);
</script>
<title>My eportfolio!</title>
</head>
<body>
<div id="my-age"></div>
</body>
</html>
Edit: I've created a new html file (the same as above) with no other content external .js files and it still doesn't work. Does this mean the age displaying code is wrong?
You may try:
document.getElementById("your_div_id").innerHTML = myAge;
if your div have an ID do this using jQuery:
$('#DivID').text(myAge);
have a class:
$('.DivClass').text(myAge);
or using only javascrtipt:
document.getElementById('DivID').innerText = myAge;
HTML:
<div id="test"></div>
JS:
var d = document.getElementById('test');
d.innerHTML = myAge;
Let's say you've got a <div> like the following one:
<div id="my-age"></div>
Then you can use the document.getElementById() to get the div in JavaScript and edit its content:
var myAgeDiv = document.getElementById('my-age');
myAgeDiv.textContent = myAge;
If your variable is your_variable
Then you can use
document.getElementById('DivID').innerHTML = your_variable;
If you are using pure javascript, somehow get your element, for example:
var myElem = document.getElementById('my-element-id');
Then you can set it's innerHTML:
myElem.innerHTML = myAge.toString();
If you are using jQuery, things get simpler, getting your element becomes:
var myElem = $('#my-element-id');
And setting it's content:
myElem.html(myAge);
Or if you don't need to insert html and want to be safer:
myElem.text(myAge);

I have a JS script in my php file, and it does not seem to be executing

This started after I converted this same script which was previously laid out in PHP to JS (I tried to change all the syntax.)
I have tried running it how it is within the php file and it didn't work :
<html>
<head>
<title>Learn | A Level Scientist</title>
<link rel="shortcut icon" href="http://www.iconj.com/ico/f/0/f0ghi1ksdc.ico" type="image/x-icon" />
<style>
#menubar {;color:white;font-size:100%;padding-top:5px;padding-bottom:5px;
border-radius:5px;margin-top: 1%;margin-bottom:1%;margin-left:4%;margin-right:4%; background: rgba(0,73,126,0.6);}
span {margin-left:2.5%;margin-right:2.5%;}
#mainsection {background: rgba(0,73,126,0.6);color:white;margin-left:4%;margin-right:4%;border-radius:5px;padding-left:20px;padding-right:20px;padding-bottom:0.5%;text-align:center;}
body {background:radial-gradient(#00477C,#002E4F);}
#horizsep {width:100%;text-align:center;color:white;padding-top:0%;padding-bottom:0%;margin:0px}
#copyright{text-align:center;}
#welcomemsg {font-size:30px;margin:0px;padding:0px}
#surroundmid{font-size:26px; padding-bottom:160px;}
#start_learning:hover {width:155px;font-size:22px;color:white;background-color:#5288AB;border-width:0px;border-radius:5px;}
#tube_part {background-color:#DB2625;margin:0%;}
#you_part {margin:0%;color:black;border-radius:30px;text-align:center}
#fb_part {background-color:#3B5998;color:white;margin:0%;text-align:center}
#acebook_part {background-color:#3B5998;margin:0%}
a{color:white; underline:none}
a:hover {color: #4DB849 ; underline:none}
a:hover {color: #4DB849 ; underline:none}
a:hover {color: #4DB849 ; underline:none}
a:clicked {color: white; underline:none}
*.menubar {border-width:0px;border-radius:1px;background:rgba(0,0,0,0.1);color:white;}
*.menubar:hover{color:white;background-color:#5288AB;border-width:0px;border-radius:1px;}
#loginform {display:inline-block;margin:0px}
#chembutton {width:30%;height:10%;font-size:40px;color:white;background:rgba(17,214,118,0.3);border-width:0px;border-radius:5px;}
#chembutton:hover {width:32%;height:11%;font-size:45px;color:white;background:rgba(17,214,118,0.5);border-width:0px;border-radius:5px;}
#chembutton:active {width:33%;height:12%;font-size:45px;color:white;background:rgba(17,214,118,0.7);border-width:0px;border-radius:5px;}
#ytvid {margin-top:0%;margin-bottom:4.7%}
#video_navigation_next {width:40%;display:inline-block;}
#video_navigation_previous {width:40%;display:inline-block;}
#interface {display:block;width:900px;height:500px;background:rgba(0,46,79,0.4);margin:auto;border-radius:5px;margin-top:5px;margin-bottom:20px;vertical-align:top;}
#output{width:550px;border-radius:5px;height:450px;background:rgba(47,94,130,0.4);display:inline-block;margin:25px;vertical-align:top;font-size:18px}
#input{width:250px;border-radius:5px;height:450px;background:rgba(47,94,130,0.4);display:inline-block;margin:25px;margin-left:0px;vertical-align:top;}
#useranswer {margin-top:40px}
#helpsection {margin:10%}
</style>
</head>
<body>
<section>
<?php
include 'C:\xampp\htdocs\ALevelScientistTesting\menubar.php' ;
?>
<div id="mainsection">
<div id="welcomemsg"><strong><u> Working out Relative Formula/Molecular Masses </u></strong></div><br>
<div id="video_navigation_previous"><br><span id="nextvid"> <!-- <= Go to the Previous Exercise --> <span></div>
<div id="video_navigation_next"><br><span id="nextvid"> Go to the Next Exercise => <span></div>
<div id="interface">
<div id="output">
<?php
//echo 'The '.$CoMo.' : '.$SubName[$FormNo].' Has a Relative '.$FoMo.' Mass of : '.$x;
//echo '<br> Work out the Relative '.$FoMo.' Mass of the '.$CoMo.' : '.$SubName[$FormNo] ;
?>
<script type="text/javascript">
document.write('The Program got to here...');
//The following 3 Arrays store 3 things. 1) The Element names. 2) The element Symbols. 3) The Relative Atomic Masses of the Elements.
var Elements = new Array("Hydrogen","Lithium","Sodium","Potassium","Rubidium","Caesium","Francium","Beryllium","Magnesium","Calcium","Strontium","Barium","Radium","Scandium","Yttrium","Lanthanum","Actinium","Titanium","Zirconium","Halfnium","Rutherfordium","Vanadium","Niobium","Tantalum","Dubnium","Chromium","Molybdenum","Tungsten","Seaborgium","Manganese","Technetium","Rhenium","Bohrium","Iron","Ruthenium","Osmium","Hassium","Cobalt","Rhodium","Iridium","Meitnerium","Nickel","Palladium","Platinum","Darmstadtium","Copper","Silver","Gold","Roentgenium","Zinc","Cadmium","Mercury","Boron","Aluminum","Gallium","Indium","Thallium","Carbon","Silicon","Germanium","Tin","Lead","Nitrogen","Phosphorus","Arsenic","Antimony","Bismuth","Oxygen","Sulfur","Selenium","Tellurium","Polonium","Flourine","Chlorine","Bromine","Iodine","Astatine","Helium","Neon","Argon","Krypton","Xenon","Radon");
var ElementsSym = new Array("H","Li","Na","K","Rb","Cs","Fr","Be","Mg","Ca","Sr","Ba","Ra","Sc","Y","La","Ac","Ti","Zr","Hf","Rf","V","Nb","Ta","Db","Cr","Mo","W","Sg","Mn","Tc","Re","Bh","Fe","Ru","Os","Hs","Co","Rh","Ir","Mt","Ni","Pd","Pt","Ds","Cu","Ag","Au","Rg","Zn","Cd","Hg","B","Al","Ga","In","Tl","C","Si","Ge","Sn","Pb","N","P","As","Sb","Bi","O","S","Se","Te","Po","F","Cl","Br","I","At","He","Ne","Ar","Kr","Xe","Rn");
var ElementsRAM = new Array("1.0","6.9","23.0","39.1","85.5","132.9","223","9.0","24.3","40.1","87.6","137.3","226","45.0","88.9","138.9","227","47.9","91.2","178.5","261","50.9","92.9","180.9","262","52.0","95.9","183.8","266","54.9","98","186.2","264","55.8","101.1","190.2","277","58.9","102.9","192.2","268","58.7","106.4","195.1","271","63.5","107.9","197.0","272","65.4","112.4","200.6","10.8","27.0","69.7","114.8","204.4","12.0","28.1","72.6","118.7","207.2","14.0","31.0","74.9","121.8","209.0","16.0","32.1","79.0","127.6","209","19.0","35.5","79.9","126.9","210","4.0","20.2","39.9","83.8","131.3","222");
// The following 3 arrays store all of the molecule names and formulas, along with the subscripted versions of all of the formulas.
var CompoundsFormula = new Array("Al2O3","NH4N3","NH4ClO3","NH4ClO4","BaCrO4","BeCO3","C6H12N2O4Pt","CrO2F2","C3Cl3N3","GaP","LiCoO2","FeLiO4P","Li2SO4","OF2","KCaCl3","Ag2CrO4","AgBF4","H3NO3S","ZnBr2","Na2CO3","BaFe2O4","BrF5","CaCrO4","H2CO3","MgCO3","AgClO3","Ag3PO4","NaPO2H2","NaMnO4","Na2S2O8");
var CompoundsName = new Array("Aluminium oxide","Ammonium azide","Ammonium chlorate","Ammonium perchlorate","Barium chromate","Beryllium carbonate","Carboplatin","Chromyl fluoride","Cyanuric chloride","Gallium phosphide","Lithium cobalt oxide","Lithium iron phosphate","Lithium sulfate","Oxygen difluoride","Potassium calcium chloride","Silver chromate","Silver fluoroborate","Sulfamic acid","Zinc bromide","Sodium carbonate","Barium ferrite","Bromine pentafluoride","Calcium chromate","Carbonic acid","Magnesium carbonate","Silver chlorate","Silver orthophosphate","Sodium hypophosphite","Sodium permanganate","Sodium persulfate");
var SubCompoundsArray = new Array("Al<sub>2</sub>O<sub>3</sub>","NH<sub>4</sub>N<sub>3</sub>","NH<sub>4</sub>ClO<sub>3</sub>","NH<sub>4</sub>ClO<sub>4</sub>","BaCrO<sub>4</sub>","BeCO<sub>3</sub>","C<sub>6</sub>H<sub>1</sub><sub>2</sub>N<sub>2</sub>O<sub>4</sub>Pt","CrO<sub>2</sub>F<sub>2</sub>","C<sub>3</sub>Cl<sub>3</sub>N<sub>3</sub>","GaP","LiCoO<sub>2</sub>","FeLiO<sub>4</sub>P","Li<sub>2</sub>SO<sub>4</sub>","OF<sub>2</sub>","KCaCl<sub>3</sub>","Ag<sub>2</sub>CrO<sub>4</sub>","AgBF<sub>4</sub>","H<sub>3</sub>NO<sub>3</sub>S","ZnBr<sub>2</sub>","Na<sub>2</sub>CO<sub>3</sub>","BaFe<sub>2</sub>O<sub>4</sub>","BrF<sub>5</sub>","CaCrO<sub>4</sub>","H<sub>2</sub>CO<sub>3</sub>","MgCO<sub>3</sub>","AgClO<sub>3</sub>","Ag<sub>3</sub>PO<sub>4</sub>","NaPO<sub>2</sub>H<sub>2</sub>","NaMnO<sub>4</sub>","Na<sub>2</sub>S<sub>2</sub>O<sub>8</sub>");
// The following 3 arrays store all the compound names and formulas, along with the subscripted versions of all the formulas.
var MoleculesFormula = new Array("C15H20O4","C12H8","CH3CO2Na","C3H4O2","C60","C6H12O6","C5H9N1O4","C5H8O4","CN","H2O2","C13H18O2","C12H22O11","C14H14O3","C10H8","C14H18N2O5","C18H22O2","C3H3O3","C7H5N1O3S1","C5H6N2O2","C3H9N","C16H13Cl1N2O1","C19H16O4","C6H3N3O6","C8H8O3","C21H22N2O2","C6H14O6","C9H11N1O6","C10H20O1","C8N8O16","C6H6N12O12","C6H5NO2");
var MoleculesName = new Array("Abscisic acid","Acenaphthylene","Sodium acetate","Acroleic acid","Buckminsterfullerene","Fructose","Glutamate","Glutaric acid","Hydrogen Cyanide","Hydrogen Peroxide","Ibuprofen","Beta-Lactose","Naproxen","Naphthalene","Aspartame","Estrone","Pyruvate","Saccharin","Thymine","Trimethylamine","Diazepam","Warfarin","Trinitrobenzene","Vanillin","Strychnine","Sorbitol","Showdomycin","Menthol","Octanitrocubane","Hexanitrohexaazaisowurtzitane","Nitrobenzene");
var SubMoleculesArray = new Array("C<sub>1</sub><sub>5</sub>H<sub>2</sub><sub>0</sub>O<sub>4</sub>","C<sub>1</sub><sub>2</sub>H<sub>8</sub>","CH<sub>3</sub>CO<sub>2</sub>Na","C<sub>3</sub>H<sub>4</sub>O<sub>2</sub>","C<sub>6</sub><sub>0</sub>","C<sub>6</sub>H<sub>1</sub><sub>2</sub>O<sub>6</sub>","C<sub>5</sub>H<sub>9</sub>N<sub>1</sub>O<sub>4</sub>","C<sub>5</sub>H<sub>8</sub>O<sub>4</sub>","CN","H<sub>2</sub>O<sub>2</sub>","C<sub>1</sub><sub>3</sub>H<sub>1</sub><sub>8</sub>O<sub>2</sub>","C<sub>1</sub><sub>2</sub>H<sub>2</sub><sub>2</sub>O<sub>1</sub><sub>1</sub>","C<sub>1</sub><sub>4</sub>H<sub>1</sub><sub>4</sub>O<sub>3</sub>","C<sub>1</sub><sub>0</sub>H<sub>8</sub>","C<sub>1</sub><sub>4</sub>H<sub>1</sub><sub>8</sub>N<sub>2</sub>O<sub>5</sub>","C<sub>1</sub><sub>8</sub>H<sub>2</sub><sub>2</sub>O<sub>2</sub>","C<sub>3</sub>H<sub>3</sub>O<sub>3</sub>","C<sub>7</sub>H<sub>5</sub>N<sub>1</sub>O<sub>3</sub>S<sub>1</sub>","C<sub>5</sub>H<sub>6</sub>N<sub>2</sub>O<sub>2</sub>","C<sub>3</sub>H<sub>9</sub>N","C<sub>1</sub><sub>6</sub>H<sub>1</sub><sub>3</sub>Cl<sub>1</sub>N<sub>2</sub>O<sub>1</sub>","C<sub>1</sub><sub>9</sub>H<sub>1</sub><sub>6</sub>O<sub>4</sub>","C<sub>6</sub>H<sub>3</sub>N<sub>3</sub>O<sub>6</sub>","C<sub>8</sub>H<sub>8</sub>O<sub>3</sub>","C<sub>2</sub><sub>1</sub>H<sub>2</sub><sub>2</sub>N<sub>2</sub>O<sub>2</sub>","C<sub>6</sub>H<sub>1</sub><sub>4</sub>O<sub>6</sub>"," C<sub>9</sub>H<sub>1</sub><sub>1</sub>N<sub>1</sub>O<sub>6</sub>","C<sub>1</sub><sub>0</sub>H<sub>2</sub><sub>0</sub>O<sub>1</sub>","C<sub>8</sub>N<sub>8</sub>O<sub>1</sub><sub>6</sub>","C<sub>6</sub>H<sub>6</sub>N<sub>1</sub><sub>2</sub>O<sub>1</sub><sub>2</sub>","C<sub>6</sub>H<sub>5</sub>NO<sub>2</sub>");
//The following part is the section where the specific Formula will be randomly selected for the questions.
var MCselection = Math.floor(Math.random()*2);
document.write(MCselection);
if(MCselection == 0) {
var Formula = CompoundsFormula;
var Name = CompoundsName;
var SubName = SubCompoundsArray;
var CoMo = 'Compound';
var FoMo = 'Formula';
} else {
var Formula = MoleculesFormula;
var Name = MoleculesName;
var SubName = SubMoleculesArray;
var CoMo = 'Molecule';
var FoMo = 'Molecular';
}
var FormNo = Math.floor(Math.random()*30);
var Form = Formula[FormNo];
var FormName = Name[FormNo];
var FormSub = SubName[FormNo];
var ElementSub = new Array();
var FoRAM = new Array();
var ElemProduct = new Array();
// Note : This is the substring Syntax : ACTUAL_STRINGHERE.substr(start,length)
// Note : is_numeric will return TRUE if the substring in question is a number. False Otherwise.
var l = 0;
var y = 0;
// The following Code is going to strip away the elements and each corresponding number of moles
// of each element per unit compound/molecule into separate arrays.
while (l < Form.length)) {
if(Form.substr(l+1,1).toLowerCase()==Form.substr(l+1,1) || !isNaN(Form.substr(l+1,1))) {
if (!isNaN(Form.substr(l+1,1))) {
Element[y] = Form.substr(l,1);
if (!isNaN(Form.substr(l+2,1))) {
ElementSub[y] = Form.substr(l+1,2);
l++;
l++;
} else {
ElementSub[y] = Form.substr(l+1,1);
l++;
}
} else {
Element[y] = Form.substr(l,2);
if (!isNaN(Form.substr(l+2,1))) {
if (!isNaN(Form.substr(l+3,1))) {
ElementSub[y] = Form.substr(l+2,2);
l+=3;
} else {
ElementSub[y] = Form.substr(l+2,1);
l+=2;
}
} else {
ElementSub[y] = 1;
l++;
}
}
} else {
Element[y] = Form.substr(l,1);
ElementSub[y] = 1;
}
l++;
y++;
}
// this resets the value of $l to 0 so that it can be recycled for another while loop.
l = 0;
x = 0;
// The following Code Identifies The Different Elements Present in the Array.
while(x < Element.length) {
while(l < ElementsSym.length) {
if (ElementsSym[l]==Element[x]) {
FoRAM[x] = ElementsRAM[l];
}
l++;
}
l = 0;
x++;
}
// this also resets the value of $l to 0 so that it can be recycled for another while loop.
l = 0;
x = 0;
// This find the product of each element multiplied by the number of moles present per mole of the formula.
while(l<Element.length) {
ElemProduct[l] = FoRAM[l]*ElementSub[l];
// echo '<br>';
l++;
}
// This finds the total of all the molar elemental products b adding up the values in an array.
//x = array_sum(ElemProduct);
var n = 0;
var sum = 0;
while(n<ElemProduct.length) {
sum += ElemProduct[n];
n++;
}
document.write("The " + CoMo + " : " + SubName[FormNo] + " Has a Relative " + FoMo + " Mass of : " + sum );
// The following Line Presents the Information.
</script>
<script type="text/javascript">
</script>
<br><hr>
</div>
<div id="input">
<form id="useranswer">
Enter Your Answer Here<br>
<input type="text" id="useranswer"><br>
<input type="submit" id="usersubmit" value="Check Answer">
</form>
<div id="helpsection">
<hr><br>
Not sure what Relative Formula mass is? <br>
<a>Click Here.</a> <br>
Not sure what Relative Molecular mass is?<br>
<a>Click Here.</a>
<br>
<hr>
<br>
Haven't learned how to work this out yet? <br>
<a>Click Here.</a>
</div>
</div>
</div>
<hr>
<span id="copyright"> Copyright A Level Scientist 2014 | All rights reserved. <span>
</div>
</section>
</body>
</html>
When I run this code at the moment, the result looks like this :
http://postimg.org/image/6993cuaqb/
Can someone please explain to me what is wrong with the code at the moment ! Thank you :)
---EDIT /
This is my new script, it kind of works, but does not. If someone would kindly test it you may get an insight into what i'm talking about (NAN, Long decimals.). When you're testing it, refresh multiple times and look at what happens.
New Script :
<html>
<head></head>
<body>
<script>
//The following 3 Arrays store 3 things. 1) The Element names. 2) The element Symbols. 3) The Relative Atomic Masses of the Elements.
var Elements = new Array("Hydrogen","Lithium","Sodium","Potassium","Rubidium","Caesium","Francium","Beryllium","Magnesium","Calcium","Strontium","Barium","Radium","Scandium","Yttrium","Lanthanum","Actinium","Titanium","Zirconium","Halfnium","Rutherfordium","Vanadium","Niobium","Tantalum","Dubnium","Chromium","Molybdenum","Tungsten","Seaborgium","Manganese","Technetium","Rhenium","Bohrium","Iron","Ruthenium","Osmium","Hassium","Cobalt","Rhodium","Iridium","Meitnerium","Nickel","Palladium","Platinum","Darmstadtium","Copper","Silver","Gold","Roentgenium","Zinc","Cadmium","Mercury","Boron","Aluminum","Gallium","Indium","Thallium","Carbon","Silicon","Germanium","Tin","Lead","Nitrogen","Phosphorus","Arsenic","Antimony","Bismuth","Oxygen","Sulfur","Selenium","Tellurium","Polonium","Flourine","Chlorine","Bromine","Iodine","Astatine","Helium","Neon","Argon","Krypton","Xenon","Radon");
var ElementsSym = new Array("H","Li","Na","K","Rb","Cs","Fr","Be","Mg","Ca","Sr","Ba","Ra","Sc","Y","La","Ac","Ti","Zr","Hf","Rf","V","Nb","Ta","Db","Cr","Mo","W","Sg","Mn","Tc","Re","Bh","Fe","Ru","Os","Hs","Co","Rh","Ir","Mt","Ni","Pd","Pt","Ds","Cu","Ag","Au","Rg","Zn","Cd","Hg","B","Al","Ga","In","Tl","C","Si","Ge","Sn","Pb","N","P","As","Sb","Bi","O","S","Se","Te","Po","F","Cl","Br","I","At","He","Ne","Ar","Kr","Xe","Rn");
var ElementsRAM = new Array(1.0,6.9,23.0,39.1,85.5,132.9,223,9.0,24.3,40.1,87.6,137.3,226,45.0,88.9,138.9,227,47.9,91.2,178.5,261,50.9,92.9,180.9,262,52.0,95.9,183.8,266,54.9,98,186.2,264,55.8,101.1,190.2,277,58.9,102.9,192.2,268,58.7,106.4,195.1,271,63.5,107.9,197.0,272,65.4,112.4,200.6,10.8,27.0,69.7,114.8,204.4,12.0,28.1,72.6,18.7,207.2,14.0,31.0,74.9,121.8,209.0,16.0,32.1,79.0,127.6,209,19.0,35.5,79.9,126.9,210,4.0,20.2,39.9,83.8,131.3,222);
// The following 3 arrays store all of the molecule names and formulas, along with the subscripted versions of all of the formulas.
var CompoundsFormula = new Array("Al2O3","NH4N3","NH4ClO3","NH4ClO4","BaCrO4","BeCO3","C6H12N2O4Pt","CrO2F2","C3Cl3N3","GaP","LiCoO2","FeLiO4P","Li2SO4","OF2","KCaCl3","Ag2CrO4","AgBF4","H3NO3S","ZnBr2","Na2CO3","BaFe2O4","BrF5","CaCrO4","H2CO3","MgCO3","AgClO3","Ag3PO4","NaPO2H2","NaMnO4","Na2S2O8");
var CompoundsName = new Array("Aluminium oxide","Ammonium azide","Ammonium chlorate","Ammonium perchlorate","Barium chromate","Beryllium carbonate","Carboplatin","Chromyl fluoride","Cyanuric chloride","Gallium phosphide","Lithium cobalt oxide","Lithium iron phosphate","Lithium sulfate","Oxygen difluoride","Potassium calcium chloride","Silver chromate","Silver fluoroborate","Sulfamic acid","Zinc bromide","Sodium carbonate","Barium ferrite","Bromine pentafluoride","Calcium chromate","Carbonic acid","Magnesium carbonate","Silver chlorate","Silver orthophosphate","Sodium hypophosphite","Sodium permanganate","Sodium persulfate");
var SubCompoundsArray = new Array("Al<sub>2</sub>O<sub>3</sub>","NH<sub>4</sub>N<sub>3</sub>","NH<sub>4</sub>ClO<sub>3</sub>","NH<sub>4</sub>ClO<sub>4</sub>","BaCrO<sub>4</sub>","BeCO<sub>3</sub>","C<sub>6</sub>H<sub>1</sub><sub>2</sub>N<sub>2</sub>O<sub>4</sub>Pt","CrO<sub>2</sub>F<sub>2</sub>","C<sub>3</sub>Cl<sub>3</sub>N<sub>3</sub>","GaP","LiCoO<sub>2</sub>","FeLiO<sub>4</sub>P","Li<sub>2</sub>SO<sub>4</sub>","OF<sub>2</sub>","KCaCl<sub>3</sub>","Ag<sub>2</sub>CrO<sub>4</sub>","AgBF<sub>4</sub>","H<sub>3</sub>NO<sub>3</sub>S","ZnBr<sub>2</sub>","Na<sub>2</sub>CO<sub>3</sub>","BaFe<sub>2</sub>O<sub>4</sub>","BrF<sub>5</sub>","CaCrO<sub>4</sub>","H<sub>2</sub>CO<sub>3</sub>","MgCO<sub>3</sub>","AgClO<sub>3</sub>","Ag<sub>3</sub>PO<sub>4</sub>","NaPO<sub>2</sub>H<sub>2</sub>","NaMnO<sub>4</sub>","Na<sub>2</sub>S<sub>2</sub>O<sub>8</sub>");
// The following 3 arrays store all the compound names and formulas, along with the subscripted versions of all the formulas.
var MoleculesFormula = new Array("C15H20O4","C12H8","CH3CO2Na","C3H4O2","C60","C6H12O6","C5H9N1O4","C5H8O4","CN","H2O2","C13H18O2","C12H22O11","C14H14O3","C10H8","C14H18N2O5","C18H22O2","C3H3O3","C7H5N1O3S1","C5H6N2O2","C3H9N","C16H13Cl1N2O1","C19H16O4","C6H3N3O6","C8H8O3","C21H22N2O2","C6H14O6","C9H11N1O6","C10H20O1","C8N8O16","C6H6N12O12","C6H5NO2");
var MoleculesName = new Array("Abscisic acid","Acenaphthylene","Sodium acetate","Acroleic acid","Buckminsterfullerene","Fructose","Glutamate","Glutaric acid","Hydrogen Cyanide","Hydrogen Peroxide","Ibuprofen","Beta-Lactose","Naproxen","Naphthalene","Aspartame","Estrone","Pyruvate","Saccharin","Thymine","Trimethylamine","Diazepam","Warfarin","Trinitrobenzene","Vanillin","Strychnine","Sorbitol","Showdomycin","Menthol","Octanitrocubane","Hexanitrohexaazaisowurtzitane","Nitrobenzene");
var SubMoleculesArray = new Array("C<sub>1</sub><sub>5</sub>H<sub>2</sub><sub>0</sub>O<sub>4</sub>","C<sub>1</sub><sub>2</sub>H<sub>8</sub>","CH<sub>3</sub>CO<sub>2</sub>Na","C<sub>3</sub>H<sub>4</sub>O<sub>2</sub>","C<sub>6</sub><sub>0</sub>","C<sub>6</sub>H<sub>1</sub><sub>2</sub>O<sub>6</sub>","C<sub>5</sub>H<sub>9</sub>N<sub>1</sub>O<sub>4</sub>","C<sub>5</sub>H<sub>8</sub>O<sub>4</sub>","CN","H<sub>2</sub>O<sub>2</sub>","C<sub>1</sub><sub>3</sub>H<sub>1</sub><sub>8</sub>O<sub>2</sub>","C<sub>1</sub><sub>2</sub>H<sub>2</sub><sub>2</sub>O<sub>1</sub><sub>1</sub>","C<sub>1</sub><sub>4</sub>H<sub>1</sub><sub>4</sub>O<sub>3</sub>","C<sub>1</sub><sub>0</sub>H<sub>8</sub>","C<sub>1</sub><sub>4</sub>H<sub>1</sub><sub>8</sub>N<sub>2</sub>O<sub>5</sub>","C<sub>1</sub><sub>8</sub>H<sub>2</sub><sub>2</sub>O<sub>2</sub>","C<sub>3</sub>H<sub>3</sub>O<sub>3</sub>","C<sub>7</sub>H<sub>5</sub>N<sub>1</sub>O<sub>3</sub>S<sub>1</sub>","C<sub>5</sub>H<sub>6</sub>N<sub>2</sub>O<sub>2</sub>","C<sub>3</sub>H<sub>9</sub>N","C<sub>1</sub><sub>6</sub>H<sub>1</sub><sub>3</sub>Cl<sub>1</sub>N<sub>2</sub>O<sub>1</sub>","C<sub>1</sub><sub>9</sub>H<sub>1</sub><sub>6</sub>O<sub>4</sub>","C<sub>6</sub>H<sub>3</sub>N<sub>3</sub>O<sub>6</sub>","C<sub>8</sub>H<sub>8</sub>O<sub>3</sub>","C<sub>2</sub><sub>1</sub>H<sub>2</sub><sub>2</sub>N<sub>2</sub>O<sub>2</sub>","C<sub>6</sub>H<sub>1</sub><sub>4</sub>O<sub>6</sub>"," C<sub>9</sub>H<sub>1</sub><sub>1</sub>N<sub>1</sub>O<sub>6</sub>","C<sub>1</sub><sub>0</sub>H<sub>2</sub><sub>0</sub>O<sub>1</sub>","C<sub>8</sub>N<sub>8</sub>O<sub>1</sub><sub>6</sub>","C<sub>6</sub>H<sub>6</sub>N<sub>1</sub><sub>2</sub>O<sub>1</sub><sub>2</sub>","C<sub>6</sub>H<sub>5</sub>NO<sub>2</sub>");
//The following part is the section where the specific Formula will be randomly selected for the questions.
var MCselection = Math.floor(Math.random()*2);
if(MCselection === 0) {
var Formula = CompoundsFormula;
var Name = CompoundsName;
var SubName = SubCompoundsArray;
var CoMo = 'Compound';
var FoMo = 'Formula';
} else {
var Formula = MoleculesFormula;
var Name = MoleculesName;
var SubName = SubMoleculesArray;
var CoMo = 'Molecule';
var FoMo = 'Molecular';
}
var FormNo = Math.floor(Math.random()*30);
var Form = Formula[FormNo];
var FormName = Name[FormNo];
var FormSub = SubName[FormNo];
var ElementSub = new Array();
var FoRAM = new Array();
var ElemProduct = new Array();
var Element = new Array();
// Note : This is the substring Syntax : ACTUAL_STRINGHERE.substr(start,length)
// Note : is_numeric will return TRUE if the substring in question is a number. False Otherwise.
var l = 0;
var y = 0;
// The following Code is going to strip away the elements and each corresponding number of moles
// of each element per unit compound/molecule into separate arrays.
while (l <= Form.length) {
if((Form.substr(l+1,1).toLowerCase()==Form.substr(l+1,1)) || (!isNaN(Form.substr(l+1,1)))) {
if (!isNaN(Form.substr(l+1,1))) {
Element[y] = Form.substr(l,1);
if (!isNaN(Form.substr(l+2,1))) {
ElementSub[y] = Form.substr(l+1,2);
l++;
l++;
} else {
ElementSub[y] = Form.substr(l+1,1);
l++;
}
} else {
Element[y] = Form.substr(l,2);
if (!isNaN(Form.substr(l+2,1))) {
if (!isNaN(Form.substr(l+3,1))) {
ElementSub[y] = Form.substr(l+2,2);
l+=3;
} else {
ElementSub[y] = Form.substr(l+2,1);
l+=2;
}
} else {
ElementSub[y] = 1;
l++;
}
}
} else {
Element[y] = Form.substr(l,1);
ElementSub[y] = 1;
}
l++;
y++;
}
document.write(Element);
// this resets the value of $l to 0 so that it can be recycled for another while loop.
l = 0;
x = 0;
// The following Code Identifies The Different Elements Present in the Array.
while(x < Element.length) {
while(l < ElementsSym.length) {
if (ElementsSym[l]==Element[x]) {
FoRAM[x] = ElementsRAM[l];
}
l++;
}
l = 0;
x++;
}
// this also resets the value of $l to 0 so that it can be recycled for another while loop.
l = 0;
x = 0;
// This find the product of each element multiplied by the number of moles present per mole of the formula.
while(l<Element.length) {
ElemProduct[l] = FoRAM[l]*ElementSub[l];
// echo '<br>';
l++;
}
// This finds the total of all the molar elemental products b adding up the values in an array.
//x = array_sum(ElemProduct);
var n = 0;
var sum = 0;
while(n<ElemProduct.length) {
sum += ElemProduct[n];
n++;
}
document.write("<br> The " + CoMo + " : " + SubName[FormNo] + " Has a Relative " + FoMo + " Mass of : " + sum );
// The following Line Presents the Information.
</script>
</body>
</html>
can someone please point me in the right direction as to why this is happening. Thank you.
You have an error on your JS code. On line 125 you have close a bracket too "while (l < Form.length)) {". Fix it by deleting one and try the code

jQuery plugin events fire only once

I am making a very minimalistic calendar plugin for the website with jQuery. I have not had much expirience with it, so I was following plugin tutorial. I have two <a> links that should change month, but unfortunately they do so only once and then both of them stop working. I suspect I have put events to a wrong place.
Sorry for quite messy code it is just a blueprint yet.
Here is the javascript.
(function($){
$.fn.extend({
jSimpleCalendar : function(currentDate)
{
return this.each(
function()
{
obj = $(this);
result = renderCalendar(currentDate);
obj.html(result);
// Event handlers
$('#JQSCMonthPrev').click(function ()
{
currentDate.setMonth(currentDate.getMonth() - 1);
result = renderCalendar(currentDate);
obj.html(result);
});
$('#JQSCMonthNext').click(function ()
{
currentDate.setMonth(currentDate.getMonth() + 1);
result = renderCalendar(currentDate);
obj.html(result);
});
});
function renderCalendar(date)
{
// Get the calendar
calendar = createMonthArray(date);
// Build xhtml
var result = '<table class="jQSCTable">';
result += '<thead><tr><td colspan=4>< ' + getMonthNames()[date.getMonth()] + ' ></td>';
result += '<td colspan=3>< ' + date.getFullYear() + ' <a href="#" id="JQSCYearNext" >></a></td></tr></thead><tbody>';
for(i=0;i<(calendar.length);i++)
{
result += '<tr>';
for (a=1; a<=7; a++)
{
result += '<td>';
if(calendar[i][a]!='N')
{
result += '<a id="JQSCLink' + calendar[i][a] + '">' + calendar[i][a] + '</a>';
}
result += '</td>';
}
result += '</tr>';
}
result += '</tbody></table>';
return result;
};
function createMonthArray(date)
{
// Get first day of month
date.setDate(1);
// Make callendar
var calendar = new Array();
// Fill empty shit from previous month
for(i=0;i<date.getDay()-1;i++)
calendar.push('N');
// Get number of days
var numberOfDays = getNumberOfDaysMonth(date);
//Fill the rest
for(i=1;i<numberOfDays+1;i++)
calendar.push(i);
// Get number of end days
var endDays = calendar.length % 7 - 1;
//Fill the empty stuff at the end
for(i=0;i<7-endDays;i++)
calendar.push('N');
//Slice to seven pieces
var slicedCalendar = new Array();
var week = 0;
slicedCalendar[0] = new Array();
for(i=1;i<calendar.length;i++)
{
slicedCalendar[week][i-week*7] = calendar[i-1];
if (((i%7)==0)&&(i!=0))
{
week++;
slicedCalendar[week] = new Array();
}
}
return slicedCalendar.splice(0, week);
};
function getNumberOfDaysMonth(date)
{
var minDays = 28;
var dateFound = false;
var oldMonth = date.getMonth();
var workDate = new Date(date.getYear(), date.getMonth(), 1);
while (!dateFound)
{
workDate.setDate(minDays+1);
var newMonth = workDate.getMonth();//new month date
if (newMonth != oldMonth)//if the month has changed
dateFound = true;
else
minDays++;
}
return minDays;
}
// Month names
function getMonthNames()
{
var month = Array();
month[0] = 'January';
month[1] = 'February';
month[2] = 'March';
month[3] = 'April';
month[4] = 'May';
month[5] = 'June';
month[6] = 'July';
month[7] = 'August';
month[8] = 'September';
month[9] = 'Octorber';
month[10] = 'November';
month[11] = 'December';
return month;
}
}
});
})(jQuery);
Here is html test.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/jSimpleCalendar.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#calendar").jSimpleCalendar(new Date());
});
</script>
</head>
<body>
<div id="calendar">
</div>
</body>
</html>
Seems like what's happening is the HTML is being rewritten when you click the first time. When this happens, the click events are no longer bound to the hrefs since the older elements were removed from the DOM.
You could put the click events into it's own function and call the function after rebuilding the calendar or use event delegation. For this, append the click event on the #calendar div and track which element was clicked.
http://www.learningjquery.com/2008/03/working-with-events-part-1

Categories