Keep the value of shopping cart after page reload - javascript

I am replicating a grocery store webpage for a course project and would like to know how to keep the values in the shopping cart even after the webpage has been refreshed. Please let me know if I havent provided enough information...
<button type="button" id="subtract" onclick="decrease()">-</button>
<input class="quantity-box" type="text" id="text" value="0">
<button type="button" id="add" onclick="increase()">+</button>
<br>
<button class="add-button" onclick="add(1)"><i class="fa fa-cart-plus"></i>&nbsp ADD TO CART</button>
<div class="cart">
<h3 class="aisle-header">Shopping Cart</h3>
<!-- list of the articles in the cart -->
<ul id="items">
</ul>
<h3 id="total" style="text-align: right;">Total: 0 $</h3>
</div>
/* This script is to add increment and decrement quanity */
function decrease(){
var textBox = document.getElementById("text");
if (textBox.value > 0){
textBox.value--;
localStorage.setItem('quantity', textBox.value);
}
}
function increase(){
var a = 1;
var textBox = document.getElementById("text");
textBox.value++;
localStorage.setItem('quantity', textBox.value);
}
window.onload = function() {
var textBox = document.getElementById("text");
textBox.value = localStorage.getItem('quantity');
}
/* This script is to add quantity to cart */
// Cost of all products in the cart
var total = 0;
// Index
var i = 1;
// List of the amount of every product in the cart
var itemCost = [];
// Add to cart
function add(n){
// Getting all Id of the selected shirt(brand ex: nike, price and quantity)
brand = "name";
priceId = "price";
quantityId = "text";
// Getting details of the selected shirt
// brand
name = document.getElementById(brand).innerHTML;
// price
price = document.getElementById(priceId).innerHTML;
// quantity
quantity = document.getElementById(quantityId).value;
// Creating a li element to add it to ul
var node = document.createElement("LI");
// id of li element
item = "item"+i;
node.setAttribute("id", item)
// cost of the selected shirt
itemCost[i-1] = Number(price) * Number(quantity);
// Updating the index i
i += 1;
// text of the li element
var textnode = document.createTextNode(name+" "+quantity+" x $"+price+" ");
// add the text to li element
node.appendChild(textnode);
// add li element to ul list
document.getElementById("items").appendChild(node);
total += Number(price) * Number(quantity);
// update the total
document.getElementById("total").innerHTML = "Total: " + total.toFixed(2) + " $";
// Add a remove button
document.getElementById(item).innerHTML += '<button class= "deleItem" onclick="deleItem('+"'"+item+"'"+')">X</button>';
// you have to respect the order of: '' and ""
}
// Remove a product from the cart
function deleItem(eId){
document.getElementById(eId).remove();
// slice is string method
// eId (element Id) contain root + number (ex: item4)
// n is the number in eId
n = Number(eId.slice(-1)) - 1;
// remove the cost of the product deleted from the cart
total -= itemCost[n];
// Updating the cost of products in the cart
document.getElementById("total").innerHTML = "Total: " + total.toFixed(2) + " $";
}
Note: I am able to use AJAX, but I am not familiar with this so if it is included in the solution a brief explanation would suffice. HTML/JAVASCRIPT/CSS/AJAX

Cookies are made for what you need to do, you can use them simply like this example with an array of elements:
var cart = ['Apple', 'Pear', 'Banana'];
var json_str = JSON.stringify(cart);
setCookie('myCart', json_str, '30'); //This cookie lasts for 30 days
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
And then you can read the cookie created earlier like this:
var json_str = getCookie('myCart');
var cart = JSON.parse(json_str);
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
To see the cookies, simply open Chrome DevTools (F12 key or Inspect), go to the Application tab and on the left you will find a menu with a Cookies item.
Remember that Chrome doesn't allow cookies for local files and consequently to save data locally you should do so:
// Save data value
localStorage.setItem("name", "John");
// Retrieve data value
var name = localStorage.getItem("name");

Related

How to access form values with variable names?

I have made a script that produces a form in a Google spreadsheet, takes its input values and appends them to the current sheet. All this works perfectly fine until I try and access the input values that have variable names.
I'm currently focusing on trying to get the inputs entered into the "Price" fields of which i are created with names "vPrice" + (i + 1) where i is the number entered previously in "Number of Variations" numVar.
In varItemAdd() I can access the values individually (vPrice1, vPrice2 etc.) and they produce the correct values. I can also access the numVar value but when I try to incrementally adjust the vPrice variable to produce each value on the spreadsheet it comes up as 'undefined'.
Script:
function varItemAdd(form) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var number = form.numVar;
var attribNumber = form.numAttr;
sheet.appendRow([form.manufacturer, number, attribNumber]);
for (i=0;i<number;i++) {
var vPrice = "vPrice" + (i + 1);
var vPriceInput = form.vPrice;
sheet.appendRow([vPriceInput, number, attribNumber]);
}
return true;
}
HTML
<body>
<form>
<!-- Select Number of Attributes to appear -->
<h2 class="title">Number of Attributes:</h2>
<input class="input-box" type="number" min="1" max="5" id="numAttr" name="numAttr" value="1"><br/>
<!-- Select Number of Variations to appear -->
<h2 class="title">Number of Variations:</h2>
<input class="input-box" type="number" id="numVar" name="numVar" value="1"><br/>
<h3 class="buttons" id="submit" onclick="addFields()">ADD</h3>
<div id="attBoxes"></div>
<div id="varBoxes"></div>
<br>
<input class="buttons" id="submit" type="button" value="SUBMIT"
onclick="google.script.run
//.withSuccessHandler(google.script.host.close)
.varItemAdd(this.parentNode)" />
<input class="buttons" id="reset" type="reset" value="RESET">
</form>
</body>
<script type='text/javascript'>
function addFields(){
// Get number of variation inputs to create
var number = document.getElementById("numVar").value;
// Get number of attribute inputs to create
var attribNumber = document.getElementById("numAttr").value;
// Get container <div>s where dynamic content will be placed
var varBoxes = document.getElementById("varBoxes");
var attBoxes = document.getElementById("attBoxes");
// Clear previous contents of the container
while (varBoxes.hasChildNodes()) {
varBoxes.removeChild(varBoxes.lastChild);
}
while (attBoxes.hasChildNodes()) {
attBoxes.removeChild(attBoxes.lastChild);
}
attBoxes.appendChild(document.createTextNode("Attribute Name(s)"));
// For each attribute append an input box inside each variation
for (k=0;k<attribNumber;k++){
var attTitle = attBoxes.appendChild(document.createElement("h2"));
var attInput = attBoxes.appendChild(document.createElement("input"));
attTitle.textContent = "Attribute " + (k + 1);
attInput.type = "text";
attInput.name = "v-att" + (k + 1);
attBoxes.appendChild(document.createElement("br"));
};
attBoxes.appendChild(document.createElement("br"));
// For each variation create inputs
for (i=0;i<number;i++){
varBoxes.appendChild(document.createTextNode("Variation " + (i+1)));
// Set variables
var skuTitle = varBoxes.appendChild(document.createElement("h2"));
var skuInput = document.createElement("input");
var priceTitle = varBoxes.appendChild(document.createElement("h2"));
var priceInput = document.createElement("input");
var attributes = varBoxes.appendChild(document.createElement("div"));
attributes.id = "varAttribs";
var varAttribs = document.getElementById("varAttribs");
// Set element values
skuTitle.textContent = "SKU";
skuInput.type = "text";
skuInput.name = "vSku";
priceTitle.textContent = "Price";
priceInput.type = "number";
priceInput.id = "vPrice" + (i + 1);
priceInput.name = "vPrice" + (i + 1);
// Call elements
varBoxes.appendChild(skuTitle);
varBoxes.appendChild(skuInput);
varBoxes.appendChild(document.createElement("br"));
varBoxes.appendChild(priceTitle);
varBoxes.appendChild(priceInput);
varBoxes.appendChild(document.createElement("br"));
for (j=0;j<attribNumber;j++){
var aValueTitle = varAttribs.appendChild(document.createElement("h2"));
var aValueInput = document.createElement("input");
aValueTitle.textContent = "Attribute " + (j + 1) + " Value";
aValueTitle.className = "title";
aValueInput.type = "text";
aValueInput.className = "input-box";
aValueInput.name = "a-value-" + (j + 1);
varBoxes.appendChild(aValueTitle);
varBoxes.appendChild(aValueInput);
varBoxes.appendChild(document.createElement("br"));
};
varBoxes.appendChild(document.createElement("br"));
varBoxes.appendChild(document.createElement("br"));
}
}
</script>
Just replace the below line in script then you should be able to access the value of each price element.
From:
var vPriceInput = form.vPrice;
To:
var vPriceInput = form[vPrice];

Update dynamically generated price of two boxes with select option

I am trying to make this work with the help of jQuery docs but not success so far.
I have two boxes paynow and payfull that has 0 initial value but I am filling these boxes dynamically (jQuery) with product prices.
Now I have to update these values further with select option to discount the price (multiply with data-percent). This is the HTML.
<select class="discount">
<option data-percent="0">Select Discount Coupon</option>
<option data-percent="5">ABCD</option>
<option data-percent="10">EFGH</option>
<option data-percent="15">IJKL</option>
</select>
<span class="price" id="paynow">$0.00</span>
<span class="price" id="payfull">$0.00</span>
EDIT: jQuery code
$(document).ready(function() {
// For Calculator
function Cost_Calculator() {
var Currency = '$';
var messageHTML = 'Please contact us for a price.';
function CostFilter(e) {
return e;
}
//Calculate function
function calculate() {
//Blank!
var CalSaveInfo = [];
$('#cost_calc_custom-data, #cost_calc_breakdown').html('');
//Calculate total
var calCost = 0;
var calculate_class = '.cost_calc_calculate';
$('.cost_calc_active').each(function() {
//Calculation
calCost = calCost + parseFloat($(this).data('value'));
//Add to list
var optionName = $(this).attr('value');
var appendName = '<span class="cost_calc_breakdown_item">' + optionName + '</span>';
var optionCost = $(this).attr('data-value');
var appendCost = '<span class="cost_calc_breakdown_price">' + Currency + optionCost + '</span>';
if (optionCost != "0") {
var appendItem = '<li>' + appendName + appendCost + '</li>';
}
//hidden data
var appendPush = ' d1 ' + optionName + ' d2 d3 ' + optionCost + ' d4 ';
$('#cost_calc_breakdown').append(appendItem);
CalSaveInfo.push(appendPush);
});
//Limit to 2 decimal places
calCost = calCost.toFixed(2);
//Hook on the cost
calCost = CostFilter(calCost);
var CustomData = '#cost_calc_custom-data';
$.each(CalSaveInfo, function(i, v) {
$(CustomData).append(v);
});
//Update price
if (isNaN(calCost)) {
$('#paynow').html(messageHTML);
$('#payfull').html(messageHTML);
$('.addons-box').hide();
} else {
$('#paynow').html(Currency + calCost);
$('#payfull').html(Currency + calCost);
$('.addons-box').show();
}
}
//Calculate on click
$('.cost_calc_calculate').click(function() {
if ($(this).hasClass('single')) {
//Add cost_calc_active class
var row = $(this).data('row');
//Add class to this only
$('.cost_calc_calculate').filter(function() {
return $(this).data('row') == row;
}).removeClass('cost_calc_active');
$(this).addClass('cost_calc_active');
} else {
// Remove class if clicked
if ($(this).hasClass('cost_calc_active')) {
$(this).removeClass('cost_calc_active');
} else {
$(this).addClass('cost_calc_active');
}
}
//Select item
var selectItem = $(this).data('select');
var currentItem = $('.cost_calc_calculate[data-id="' + selectItem + '"]');
var currentRow = currentItem.data('row');
if (selectItem !== undefined) {
if (!$('.cost_calc_calculate[data-row="' + currentRow + '"]').hasClass('cost_calc_active'))
currentItem.addClass('cost_calc_active');
}
//Bring in totals & information
$('#cost_calc_breakdown_container, #cost_calc_clear_calculation').fadeIn();
$('.cost_calc_hide').hide();
$('.cost_calc_calculate').each(function() {
calculate();
});
return true;
});
$('#cost_calc_clear_calculation').click(function() {
$('.cost_calc_active').removeClass('cost_calc_active');
calculate();
$('#cost_calc_breakdown').html('<p id="empty-breakdown">Nothing selected</p>');
return true;
});
}
//Run cost calculator
Cost_Calculator();
});
How about this one:
var totalPayNowPrice=parseFloat($('#paynow').text());
var totalPayFullPrice=parseFloat($('#payfull').text());
$('.discount').on('change',function(){
if(parseInt($('.discount option:selected').attr('data-percent'))){
$('#paynow').text((totalPayNowPrice*parseInt($('.discount option:selected').attr('data-percent')))+'$');
$('#payfull').text((totalPayFullPrice*parseInt($('.discount option:selected').attr('data-percent')))+'$');
}
});
Just put the $ sign in you spans after the numbers, in order to parse function would work.
JSFIDDLE
UPDATE
From another point I think there is a better solution to use prototype and store you current prices in spans inside global variable, then you can use them wherever you want. Here the pseudo prototype for your use, if you`d like just customize it for you using:
function Test(){
this.totalPayNowPrice=1;//the is 1 only for check code working
this.totalPayFullPrice=1;
}
Test.prototype={
init: function(){
var scope=this;
$('.discount').on('change',function(){
if(parseInt($('.discount option:selected').attr('data-percent'))){
$('#paynow').text((scope.totalPayNowPrice*parseInt($('.discount option:selected').attr('data-percent')))+'$');
$('#payfull').text((scope.totalPayFullPrice*parseInt($('.discount option:selected').attr('data-percent')))+'$');
}
},
updatePaynowPrice:function(newPrice){
this.totalPayNowPrice=totalPayNowPrice;
},
updatePayfullPrice:function(newPrice){
this.totalPayFullPrice=totalPayNowPrice;
}
}
you can use
$(document).ready(function(){
// get price from #paynow (just a number)
var getPaynow = $('#paynow').text().match(/\d+/);
// get price from #payfull (just a number)
var getPayfull = $('#payfull').text().match(/\d+/);
$('.discount').on('change', function(){
// get data-percent from selected option
var discount = parseFloat($(this).find('>option:selected').attr('data-percent'));
//alert(discount +'///'+ getPaynow+'///'+ getPayfull);
//update price for #paynow and #payfull
$('#paynow').text('$'+parseFloat(getPaynow - (getPaynow * discount / 100)));
$('#payfull').text('$'+parseFloat(getPayfull - (getPayfull * discount / 100)));
});
});
Working Demo
in your code you can update prices after this part of code
//Update price
if (isNaN(calCost)) {
$('#paynow').html(messageHTML);
$('#payfull').html(messageHTML);
$('.addons-box').hide();
} else {
$('#paynow').html(Currency + calCost);
$('#payfull').html(Currency + calCost);
$('.addons-box').show();
}
//get price from #paynow (just a number)
getPaynow = $('#paynow').text().match(/\d+/);
// get price from #payfull (just a number)
getPayfull = $('#payfull').text().match(/\d+/);

Storing the clicked value in radio buttonswith cookies [duplicate]

This question already has answers here:
Keep the selected option saved within js
(4 answers)
Closed 8 years ago.
Hey guys am new to js actually..I have two radio buttons and a save button..The code i have done
<input id="male" type="radio" name="sex" id="male" value="male">Male
<input id="female" type="radio" name="sex" id="female" value="female">Female
<button id="buttons">Save me </button>
<script>
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}
var c = document.getElementById('buttons');
c.onclick = function() {
var c = document.getElementById('male');
var m = document.getElementById('female');
if(c.checked == 'true') {
setCookie('samplecookie', c.value, 30 );
} else if(n.checked == 'true') {
setCookie('anothersamplecookie', n.value, 30);
}
}
</script>
What should i need to do.
Suppose i clicked on the female radio button and click the save button the value needs to be stored and the value will remain be checked even the page is refreshed..The above code didnt works for me ..The radio button gets unchecked when the page is refreshed..
I have asked a similar qus here.But it didnt helped me ..I have heard this can be done with localstorage too..But i dont reall know how to.
Hope you guys would help me with the right code and will be really appreciated..
You need to set AND get the cookie.
FIDDLE
function setCookie(name, value, days) { // from http://www.quirksmode.org/js/cookies.html
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
} else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
window.onload = function () {
var gender = getCookie('samplecookie');
if (gender) {
if (gender=="male") document.getElementById('male').click(); // or .checked=true;
else if (gender=="female") document.getElementById('female').click();
}
document.getElementById('buttons').onclick = function () {
var m = document.getElementById('male');
var f = document.getElementById('female');
if (m.checked) {
setCookie('samplecookie', m.value, 30);
} else if (f.checked) {
setCookie('samplecookie', f.value, 30);
}
}
}
I don't know if this is something you'd want. But a thing that comes up to mind is the HTML5 Web Storage functionality.With that feature you can store data on the computer of the user.
So whenever a user changes an input field you can create a javascript call that stores the value into the localstorage:
localStorage.setItem(“inputName”, “value”);
Then when you load the page, you see if any of these values are stored and then fill them in.

Sort a list by Days of the week

I have created a list of items that contains information such as a taskname (i.e. take out the garbage), who must do the task, and what day of the week the task needs to be done by. All this information is gathered through text inputs in the html, then displayed as a list item using JavaScript.
Im wondering if there is a simple way to sort my list by the day of the week the task needs to be done. I was thinking perhaps i should add numerical value of 1-7 to strings containing days of the week. (for instance one that contains monday would have a value of 1, ones that have sunday have a value of 7). Then i could sort these numerically.
If anyone could show me how to do this with JavaScript (not jQuery), or an easier way, that would be greatly appreciated. (The more comments in the code the better).
Thanks
//links html elements to corresponding javascript variable names
var allTasks = document.getElementById('allTasks');
var taskInput = document.getElementById('taskInput');
var personInput = document.getElementById('personInput');
var dayInput = document.getElementById('dayInput');
var addBtn = document.getElementById('addBtn');
var sortBtn = document.getElementById('sortBtn');
//Create Task List based on input put in text fields
var TaskObject = function(taskText, personText, dayText){
var self = this;
self.name="taskName";
self.listItem;
self.init = function(){
//create html elements
self.listItem = document.createElement("li");
//create text box and have it display information from the previous inputed task
var text = document.createElement("text");
text.innerText = taskText + " ";
//create text box and have it display information from the previous inputed person
var text2 = document.createElement("text");
text2.innerText = personText + " ";
//create text box and have it display information from the previous inputed day of the week
var text3 = document.createElement("text");
text3.innerText = dayText + " ";
//create delete button and functionality
var deleteBtn = document.createElement("button");
deleteBtn.innerHTML = "delete";
deleteBtn.onclick = self.deleteMe;
// combine html elements
self.listItem.appendChild(text);
self.listItem.appendChild(text2);
self.listItem.appendChild(text3);
self.listItem.appendChild(deleteBtn);
allTasks.appendChild (self.listItem);
}
self.deleteMe = function(){
var parent = self.listItem.parentNode;
parent.removeChild(self.listItem);
}
}
addBtn.onclick = function (){
var newTask = new TaskObject(taskInput.value, personInput.value, dayInput.value)
newTask.init();
}
There is an in-built javascript function that helps in getting the day of the week.
//Calling the date function
var date = new Date();
//Getting the day of the week
var day_of_week = date.getDay();
date.getDay() returns a value from 0 to 6 for sunday to saturday respectively
//A function to get the day of the week
function dayOfTheWeek()
{
var date = new Date();
var day_of_week = date.getDay();
switch (day_of_week)
{
case 0: return "sunday"
case 1: return "monday"
case 2: return "tuesday"
case 3: return "wednessday"
case 4: return "thursday"
case 5: return "friday"
default: return "saturday"
}
}
//Calling the function
var day_of_week_in_string = dayOfTheWeek();
(javascript)
//define your task objects as an array (outside of TaskObject)
var tasks = [];
//retrieve a number rather than a text value
var dayInput = document.getElementById('dayInput').selectedIndex
var newTask = ...
//add this task object to the Task array
tasks.push(newTask)
//now you can sort the array:
tasks.sort(function(a, b){return a.dayInput-b.dayInput});
(html)
<select id="dayInput">
<option value="0">Monday</option>
<option value="1">Tuesday</option>
<option value="2">Wednesday</option>
<option value="3">Thursday</option>
<!-- etc.. -->
</select>
Here is my solution to your problem. When a new li is created, you store a hidden attribute called "data-day-text" and attach it to the li. When you sort, you remove the ul from the DOM (for performance gains), sort the lis according to the data-day-text, then re-attach the lis and the ul.
http://jsfiddle.net/g3et9abh/3/
html:
<div id="allTasksContainer">
<ul id="allTasks"></ul>
</div>
<p>task:
<input type="text" id="taskInput" />
</p>
<p>person:
<input type="text" id="personInput" />
</p>
<p>day:
<input type="text" id="dayInput" />
</p>
<button id="addBtn">add</button>
<button id="sortBtn">sort</button>
javascript:
//links html elements to corresponding javascript variable names
var allTasksContainer = document.getElementById('allTasksContainer');
var allTasks = document.getElementById('allTasks');
var taskInput = document.getElementById('taskInput');
var personInput = document.getElementById('personInput');
var dayInput = document.getElementById('dayInput');
var addBtn = document.getElementById('addBtn');
var sortBtn = document.getElementById('sortBtn');
//Create Task List based on input put in text fields
var TaskObject = function (taskText, personText, dayText) {
var self = this;
self.name = "taskName";
self.listItem;
self.init = function () {
//create html elements
self.listItem = document.createElement("li");
self.listItem.dataset.dayText = dayText;
//create text box and have it display information from the previous inputed task
var text = document.createElement("text");
text.innerText = taskText + ' ' + personText + ' ' + dayText;
//create delete button and functionality
var deleteBtn = document.createElement("button");
deleteBtn.innerHTML = "delete";
deleteBtn.onclick = self.deleteMe;
// combine html elements
self.listItem.appendChild(text);
self.listItem.appendChild(deleteBtn);
allTasks.appendChild(self.listItem);
}
self.deleteMe = function () {
var parent = self.listItem.parentNode;
parent.removeChild(self.listItem);
}
}
addBtn.onclick = function () {
var newTask = new TaskObject(taskInput.value, personInput.value, dayInput.value)
newTask.init();
}
sortBtn.onclick = function () {
allTasksContainer.removeChild(allTasks);
var nodes = [].slice.call(allTasks.getElementsByTagName('li'), 0);
[].sort.call(nodes, function (a, b) {
return b.dataset.dayText < a.dataset.dayText ? 1 : b.dataset.dayText > a.dataset.dayText ? -1 : 0;
});
while (allTasks.firstChild) {
allTasks.removeChild(allTasks.firstChild);
}
nodes.forEach(function (node) {
allTasks.appendChild(node);
});
allTasksContainer.appendChild(allTasks);
}

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

Categories