I am trying to make a simple game, in the below function handCricketBat(), the if conditional statement is getting skipped even when the condition batsMan = bowlerMan is satisfied. It always moves on to the else statement. Can someone tell me why this is happening.
function handCricketBat(){
var total = 0;
for (x = 1; x <=6; x++){
var batsMan = prompt("Ball " + x + " \nEnter Between 1-6");
var bowlerMan = randomBall();
console.log("The bowler - "+ bowlerMan);
if (batsMan === bowlerMan) {
console.log("Howzattt");
break;
}
else if (batsMan !== bowlerMan) {
console.log("That's good batiing, scoring a " + batsMan);
continue;
}
total += +batsMan;
}
console.log(total);
}
function randomBall(){
return Math.floor(Math.random()*7);
}
Your batsMan is a string.
Use var batsMan = parseInt(prompt("Ball " + x + " \nEnter Between 1-6")); instead and it should work.
Related
This calculator is designed to accept user input for the purpose of calculating and reporting average temperatures. I've got the it completed for the most part but I'm running into an issue where low temps that have a different amount of digits than the high, example: 9 and 10 or 95 and 110, the script is valuing the low temp higher than the high temp. Under neath is the javascript I'm using. Unfortunately I can't add a screenshot yet but the output response on entering a low of 9 and a high of 10 is:
Please enter a low temperature less than the high temperature.
(function(){
var temperatures = [];
var lowest = 150;
var highest = 0;
var lowestDate;
var highestDate;
var lAverage = 0;
var hAverage = 0;
var table = $('table');
function addTemps() {
'use strict';
var table = "<table><tr><th style='width:110px'>Date</th><th>Low Temperature</th><th>High Temperature</th></tr>";
var lTemp = $('lTemp').value;
var hTemp = $('hTemp').value;
if (((parseFloat(lTemp) != parseInt(lTemp, 10)) || isNaN(lTemp) ||
(parseFloat(hTemp) != parseInt(hTemp, 10)) || isNaN(hTemp)) ||
(lTemp > 150) || (hTemp < 0) || (lTemp>hTemp)) {
if ((parseFloat(lTemp) != parseInt(lTemp, 10)) || isNaN(lTemp)){
table += '<tr><td colspan="3">Please enter a number for low temperature.</td></tr></table>';
}
if ((parseFloat(hTemp) != parseInt(hTemp, 10)) || isNaN(hTemp)){
table += '<tr><td colspan="3">Please enter a number for high temperature.</td></tr></table>';
}
if ((lTemp > 150) || (hTemp < 0)) {
table += '<tr><td colspan="3">Please enter a number below 150 for low, or a number greater than 0 for high temperature.</td></tr></table>';
}
if (lTemp>hTemp) {
table += '<tr><td colspan="3">Please enter a low temperature less than the high temperature.</td></tr></table>';
}
$('output').innerHTML = table;
}
else {
lTemp = parseInt(lTemp);
hTemp = parseInt(hTemp);
var newDate = new Date((new Date().getTime())-(temperatures.length * 86400000));
temperatures.push([newDate,lTemp,hTemp]);
table = createTable(table);
$('output').innerHTML = table;
}
return false;
}
function init() {
'use strict';
$('theForm').onsubmit = addTemps;
}
function createTable(tbl){
lAverage=0; hAverage=0;
for (var i = 0; i<temperatures.length; i++) {
var date = ''+(temperatures[i][0].getMonth()+1)+"/"+temperatures[i][0].getDate()+"/"+temperatures[i][0].getFullYear();
var low = temperatures[i][1];
var high = temperatures[i][2];
tbl += '<tr><td>'+date+'</td><td style="text-align: right">'+low+'</td><td style="text-align: right">'+high+'</td></tr>';
if (low < lowest){
lowest = low;
lowestDate = date;
}
if (high > highest){
highest = high;
highestDate = date;
}
lAverage+=temperatures[i][1];
hAverage+=temperatures[i][2];
}
lAverage=(lAverage/temperatures.length).toFixed(1);
hAverage=(hAverage/temperatures.length).toFixed(1);
tbl+='<tr class="summaryRow"><td>Averages</td><td style="text-align: right">'+lAverage+'</td><td style="text-align: right">'+hAverage+'</td></tr>';
tbl+='<tr class="summaryRow"><td colspan="3">The lowest temperature of '+lowest+' occured on '+lowestDate+'.</tr>';
tbl+='<tr class="summaryRow"><td colspan="3">The highest temperature of '+highest+' occured on '+highestDate+'.</tr>';
tbl+='</table>';
return tbl;
}
function $(elementID){
if (typeof(elementID) == 'string') {
return document.getElementById(elementID);
}
}
window.onload = init;
})();
I'm assuming this is an error in the addTemps function with parseFloat or parseInt but I'm stuck on what to actually modify to avoid this issue.
Here are some thoughts. I could not test this code in repl.it, so it might have some rough edges.
If I correctly understand what this code is supposed to do..
Two main issues were:
You were comparing strings to numbers in several locations.
Your addTemps() function always returned false -- is this correct?
I actually don't remember how onSubmit works as I've not used JQuery or forms in ages.
Adjust the return value from addTemps appropriately, if I got that part mixed up.
Not technically wrong, but you can use "convenience variables" to cache calculations/conversions. They are essentially "free" in JS. This can make Code easier to read, and compiler doesn't have to keep re-doing the same calc.
(function(){
// could avoid "magic numbers" in code with:
var min_valid_hiTemp = 0;
var max_valid_loTemp = 150;
// initialize vars
var temperatures = [];
var lowest = 150; // max_valid_loTemp;
var highest = 0; // min_valid_hiTemp;
var lowestDate = '';
var highestDate = '';
var lAverage = 0;
var hAverage = 0;
var table = $('table');
function addTemps() {
'use strict';
var table = "<table><tr><th style='width:110px'>Date</th><th>Low Temperature</th><th>High Temperature</th></tr>";
var lTemp = $('lTemp').value;
var hTemp = $('hTemp').value;
// convenience variables
loTemp_float = parseFloat(lTemp);
loTemp_int = parseInt(lTemp, 10);
hiTemp_float = parseFloat(hTemp);
hiTemp_int = parseInt(hTemp, 10);
loTemp_isNAN = isNaN(lTemp);
hiTemp_isNAN = isNaN(hTemp);
// print error message if input was invalid
if ( (loTemp_float != loTemp_int) ||
(hiTemp_float != hiTemp_int) ||
loTemp_inNaN || hiTemp_isNan ||
(loTemp_int > hiTemp_int) ||
(loTemp_int > 150) ||
(hiTemp_int < 0)
){
if ((loTemp_float != loTemp_int) || loTemp_isNAN){
table += '<tr><td colspan="3">Please enter a number for low temperature.</td></tr></table>';
}
if ((hiTemp_float != hiTemp_int) || hiTemp_isNAN){
table += '<tr><td colspan="3">Please enter a number for high temperature.</td></tr></table>';
}
// uses "magic numbers"
if ((loTemp_int > 150) || (hiTemp_int < 0)) {
table += '<tr><td colspan="3">Please enter a number below 150 for low, or a number greater than 0 for high temperature.</td></tr></table>';
}
if (loTemp_int > hiTemp_int) {
table += '<tr><td colspan="3">Please enter a low temperature less than the high temperature.</td></tr></table>';
}
// don't call createTable() ?
$('output').innerHTML = table;
// shouldn't this block return false? - To not submit the form
return false
}
// input is valid: store the temperature data
else {
// not necessary now - we already have variables with this info: loTemp_int, hiTemp_int
// lTemp = parseInt(lTemp);
// hTemp = parseInt(hTemp);
// curious how the number of stored temps is related to the date..?
var newDate = new Date((new Date().getTime())-(temperatures.length * 86400000));
// just use the variables we already have
//temperatures.push([newDate, lTemp, hTemp]);
temperatures.push([newDate, loTemp_int, hiTemp_int]);
table = createTable(table);
$('output').innerHTML = table;
// shouldn't this block return true? - To submit the form
return true
}
// ?? No matter what, return false?
// I suspect you want to return false if input was invalid, and true if it was valid.
// if so, the return values should be inside the "if" and the "else" blocks.
// Not outside both blocks, as it is here.
//return false;
}
function init() {
'use strict';
$('theForm').onsubmit = addTemps;
}
function createTable(tbl){
lAverage=0;
hAverage=0;
for (var i = 0; i<temperatures.length; i++) {
var date = ''+(temperatures[i][0].getMonth()+1)+"/"+temperatures[i][0].getDate()+"/"+temperatures[i][0].getFullYear();
var low = temperatures[i][1];
var high = temperatures[i][2];
tbl += '<tr><td>'+date+'</td><td style="text-align: right">'+low+'</td><td style="text-align: right">'+high+'</td></tr>';
if (low < lowest){
lowest = low;
lowestDate = date;
}
if (high > highest){
highest = high;
highestDate = date;
}
// you already have variables "low" and "high" - may as well use them
// lAverage+=temperatures[i][1];
// hAverage+=temperatures[i][2];
lAverage += low;
hAverage += high;
}
lAverage=(lAverage/temperatures.length).toFixed(1);
hAverage=(hAverage/temperatures.length).toFixed(1);
tbl+='<tr class="summaryRow"><td>Averages</td><td style="text-align: right">'+lAverage+'</td><td style="text-align: right">'+hAverage+'</td></tr>';
tbl+='<tr class="summaryRow"><td colspan="3">The lowest temperature of '+lowest+' occured on '+lowestDate+'.</tr>';
tbl+='<tr class="summaryRow"><td colspan="3">The highest temperature of '+highest+' occured on '+highestDate+'.</tr>';
tbl+='</table>';
return tbl;
}
function $(elementID){
if (typeof(elementID) == 'string') {
return document.getElementById(elementID);
}
}
window.onload = init;
})();
I actually don't remember how onSubmit works as I've not used JQuery or forms in ages.
Adjust the return value from addTemps appropriately, if I got that part mixed up.
Here is a repl version, that also corrects a couple typos that exist in the above code.
note: none of the "print" statements will appear until you reply to the "add another temp" prompt with something other than y. So that part of the functionality is not perfect, but you can see that the main sticky points of the logic have been correctly addressed.
// could avoid "magic numbers" in code with:
var min_valid_hiTemp = 0;
var max_valid_loTemp = 150;
// initialize vars
var temperatures = [];
var lowest = 150; // max_valid_loTemp;
var highest = 0; // min_valid_hiTemp;
var lowestDate = '';
var highestDate = '';
var lAverage = 0;
var hAverage = 0;
// var table = $('table');
// non html version
var table = 'table\n';
function addTemps() {
'use strict';
var table = 'Date' + ' ' + 'Low Temperature' + ' ' + 'High Temperature' + '\n';
// var lTemp = $('lTemp').value;
// var hTemp = $('hTemp').value;
// non html version:
var lTemp = prompt('enter low temp');
var hTemp = prompt('enter high temp');
// convenience variables
var loTemp_float = parseFloat(lTemp);
var loTemp_int = parseInt(lTemp, 10);
var hiTemp_float = parseFloat(hTemp);
var hiTemp_int = parseInt(hTemp, 10);
var loTemp_isNAN = isNaN(lTemp);
var hiTemp_isNAN = isNaN(hTemp);
// print error message if input was invalid
if ( (loTemp_float != loTemp_int) ||
(hiTemp_float != hiTemp_int) ||
loTemp_isNAN || hiTemp_isNAN ||
(loTemp_int > hiTemp_int) ||
(loTemp_int > 150) ||
(hiTemp_int < 0)
){
if ((loTemp_float != loTemp_int) || loTemp_isNAN){
table += 'Please enter a number for low temperature.' + '\n';
}
if ((hiTemp_float != hiTemp_int) || hiTemp_isNAN){
table += 'Please enter a number for high temperature.' + '\n';
}
// uses "magic numbers"
if ((loTemp_int > 150) || (hiTemp_int < 0)) {
table += 'Please enter a number below 150 for low, or a number greater than 0 for high temperature.' + '\n';
}
if (loTemp_int > hiTemp_int) {
table += 'Please enter a low temperature less than the high temperature.' + '\n';
}
// does't call createTable() ?
// $('output').innerHTML = table;
// without html:
console.log(table);
console.log();
// shouldn't this block return false? - To not submit the form
return false
}
// input is valid: store the temperature data
else {
// curious how the number of stored temps is related to the date..?
var newDate = new Date((new Date().getTime()) - (temperatures.length * 86400000));
temperatures.push([newDate, loTemp_int, hiTemp_int]);
table = createTable(table);
//$('output').innerHTML = table;
// non html version
console.log(table);
console.log();
// shouldn't this block return true? - To submit the form
return true
}
// ?? No matter what, return false?
// I suspect you want to return false if input was invalid, and true if it was valid.
// if so, the return values should be inside the "if" and the "else" blocks.
// Not outside both blocks, as it is here.
//return false;
}
function init() {
'use strict';
//$('theForm').onsubmit = addTemps;
// non html / jquery version
if (addTemps()){
console.log("submitted");
}
else {
console.log('not submitted');
}
}
function createTable(tbl){
lAverage=0;
hAverage=0;
for (var i = 0; i< temperatures.length; i++) {
var date = '' + (temperatures[i][0].getMonth()+1) +
"/" + temperatures[i][0].getDate() +
"/" + temperatures[i][0].getFullYear();
var low = temperatures[i][1];
var high = temperatures[i][2];
tbl += date + '\t' + low + '\t\t\t' + high + '\n';
if (low < lowest){
lowest = low;
lowestDate = date;
}
if (high > highest){
highest = high;
highestDate = date;
}
lAverage += low;
hAverage += high;
}
lAverage = (lAverage/temperatures.length).toFixed(1);
hAverage = (hAverage/temperatures.length).toFixed(1);
tbl += 'Averages' + '\t' + lAverage + ' low, ' + '\t\t' + hAverage + ' high' + '\n';
tbl += 'The lowest temperature of ' + lowest + ' occured on ' + lowestDate +'.\n';
tbl += 'The highest temperature of ' + highest + ' occured on ' + highestDate+'.\n';
tbl += '\n';
return tbl;
}
// window.onload = init;
var addAnother = 'y'
while (addAnother == 'y') {
init();
addAnother = prompt('press "y" to add another');
}
I keep getting this error due to these two lines:
document.getElementById('button').innerHTML = '<p><button
onClick = "MultiAnswer('+ questions[output] + ',' + answer[output]
+');">Submit</button></p>';
And I can't figure out what I am missing .
Edit: Here is the surrounding code (Excuse the mess) Contains methods that uses a switch statement to determine the input for the arrays required, from there puts it into the parameters for DisplayQuestion which then passes it to the functions below from the behaviour wanted:
function MultiQuest(questions, choices, answer){
var output = Math.floor(Math.random() * (questions.length));
var choicesOut = [];
document.getElementById('question').innerHTML = '<p id = "Q1">' + questions[output] + '<p><br>';
for(var k = 0;k < choices[output].length; k++ ){
choicesOut.push('<p><input id = "choice'+[k]+'" type = "radio" name = "option" value="'+choices[output][k]+'">' + choices[output][k] + '<p>');
}
document.getElementById('answers').innerHTML = choicesOut.join("");
document.getElementById('button').innerHTML = '<p><button onClick = "MultiAnswer('+ questions[output] + ',' + answer[output] +');">Submit</button></p>';
document.getElementById('score').innerHTML = '<p>' + score + '<p>';
}
function MultiAnswer(questions, answer, pageType){
var currentQuestion = document.getElementById('Q1').textContent;
var number = multiQuestions(currentQuestion, questions);
var correctAnswer = answer[number];
var givenAnswer;
var options = document.getElementsByName('option');
var i
for(i = 0; i < options.length; i++){
if(options[i].checked){
givenAnswer = options[i].value;
}
}
if(givenAnswer == correctAnswer){
alert("Right Answer!");
score++;
} else {
alert("Wrong Answer!");
score = 0;
}
i = 0;
DisplayQuestion(pageType);
}
function multiQuestions(currentQuestion, whichArray){
for(var i = 0; i < multiquestions.length; i++){
if(currentQuestion == whichArray[i]){
return i;
}
}
return null;
}
You cannot have a function call like this:
MultiAnswer('+ questions[output] + ',' + answer[output]
+')
You will need to evaluate the parameter in a seperate variable and then pass it in the function.
So in your onClick call of multiAnswer you have wrapped the 3 inputs in quotes. After referencing your multiAnswer function you do have the 3 inputs that you are looking for. You also have + signs on the ends of those inputs. You do not need to concatenate the parens inside of the function call.
I hope this helps!
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions
onClick = "MultiAnswer(questions[output] + ',' + answer[output]
)">Submit</button></p>';
I have an image I'm trying to shake when a user guesses the name of a fish wrong. I'm using a conditional ng-class="{'shake':error}". However, even when the answer is correct the image shakes. I don't believe that at anytime $scope.error is set to true. What am I missing here?
codepen
I think what you want to do is return guessIsCorrect or guessIsWrong from your compare function.
$scope.compare = function(guess) {
guess = guess.replace(/\s/g, '').toLowerCase();
var answers = [];
answers.push($scope.name.replace(/\s/g, '').toLowerCase());
currentAnimal.alts.forEach(function(alt) {
answers.push(alt.toLowerCase().replace(/\s/g, ''));
});
//console.log(answers);
//console.log("Guess: " + guess + "\n");
//console.log("Answer: " + answers + "\n");
for (var x = 0; x <= answers.length; x++) {
if (guess === answers[x]) {
return guessIsCorrect();
}
if (x === answers.length) {
return guessIsWrong();
}
}
};
Need help, because I have an error in my code and I can't see it.
I'm trying to do a newton raphson method.
The user enters a polinomy and the function calculates the derivate, then applys the Newton's raphson formula and shows the final result in a table.
My problem is that I can't make it work, because I can't show the final table with the results.
See an example here: http://codepen.io/anon/pen/Qyddoy?editors=101
Thats my JS code.
function funcion(func, x) {
var nuevaFuncion= func.replace(/x/g, x);
return eval(nuevaFuncion);
}
function derivada(x) {
var func = document.getElementsByName("func")[0].value.trim();
var derivative = nerdamer('diff(' + func + ')').evaluate();
}
function procesar(formulario) {
var i = 0;
var func = document.getElementsByName("func")[0].value;
var err, x_1, x = parseFloat(formulario.x.value);
var resultado = '<table border="3"><tr><td align="center">i</td><td align="center">x<sub></sub></td><td align="center">error</td></tr>';
do {
x_1 = x;
x = x - funcion(func, x) / derivada(x);
err = Math.abs((x - x_1) / x);
resultado += '<tr><td>x<sub>' + i + '</sub></td><td>' + x_1 + '</td><td>' + err + '</td></tr>';
i++;
} while (x != x_1 && i < 100);
document.getElementById('resultado').innerHTML = resultado + '</tbody> </table><br>' + (i == 100 ? 'La solucion no es convergente. ' : 'La solucion es ' + x);
return false;
}
There are a few things that I would do differently. The first is that I would avoid replacing and using eval and let nerdamer do the work. For example sin(x) would give an error since there isn't a native JS function called sin but rather Math.sin. I'm guessing your i < 100 is a safety. I prefer using a break statement since this is a lot easier to read and debug in my opinion. Also if you already know the variable name you can avoid calling buildFunction and use evaluate instead for example if the variable is x
nerdamer(func).evaluate({x:x});
And lastly, Newton's method requires some stop condition up to some accuracy. Your stop condition of x != x_1 is risky at best.
Here are my edits
http://codepen.io/anon/pen/gPgXbK?editors=101
function funcion(func, x) {
return nerdamer(func).buildFunction().call(undefined, x);
}
function derivada(x){
var func = document.getElementsByName("func")[0].value.trim();
return nerdamer('diff(' + func + ')').buildFunction().call(undefined, x);
}
function procesar(formulario) {
var i = 0;
var func = document.getElementsByName("func")[0].value;
var err, x_1, x = parseFloat(formulario.x.value);
var resultado = '<table border="3"><tr><td align="center">i</td><td align="center">x<sub></sub></td><td align="center">error</td></tr>';
do {
var x_1 = x - funcion(func, x) / derivada(x);
//get the error
var e = Math.abs(x-x_1);
x = x_1
err = Math.abs((x - x_1) / x);
resultado += '<tr><td>x<sub>' + i + '</sub></td><td>' + x_1 + '</td><td>' + err + '</td></tr>';
i++;
//I imagine that this is your safety so I would implement it like this
if(i > 100) break;
} while (e > 0.01);
document.getElementById('resultado').innerHTML = resultado + '</tbody></table><br>' + (i == 100 ? 'La solucion no es convergente. ' : 'La solucion es ' + x);
return false;
}
The function derivada doesn't return nothing so the division in procesar function fails.
You have to return a value so the calculus can go ahead. And I think you want to return the result of derivating the function, like this:
function derivada(x) {
var func = document.getElementsByName("func")[0].value.trim();
var derivative = nerdamer('diff(' + func + ')').evaluate();
return eval(derivative.text());
}
The following code is giving me an error in the chrome developer tools:
"uncaught syntax error- unexpected token"
Specifically, the Errors come up in the populate header function at
var notraw = JSON.parse(arrayraw)
and in the first if statement, at
parsed = JSON.parse(retrieved); //var test is now re-loaded!
These errors haven't come up in previous iterations. Does anyone know why?
// This statement should be ran on load, to populate the table
// if Statement to see whether to retrieve or create new
if (localStorage.getItem("Recipe") === null) { // if there was no array found
console.log("There was no array found. Setting new array...");
//Blank Unpopulated array
var blank = [
["Untitled Recipe", 0, 0]
];
// Insert Array into local storage
localStorage.setItem("Recipe", JSON.stringify(blank));
console.log(blank[0]);
} else {
console.log("The Item was retrieved from local storage.");
var retrieved = localStorage.getItem("Recipe"); // Retrieve the item from storage
// test is the storage entry name
parsed = JSON.parse(retrieved); //var test is now re-loaded!
// we had to parse it from json
console.log(parsed)
}
// delete from array and update
function deletefromarray(id) {
var arrayraw = localStorage.getItem("Recipe")
var notraw = JSON.parse(arrayraw)
console.log(notraw[id])
notraw.splice(id, 1);
localStorage.setItem("Recipe", JSON.stringify(notraw));
}
// This adds to local array, and then updates that array.
function addtoarray(ingredient, amount, unit) {
var arrayraw = localStorage.getItem("Recipe")
var notraw = JSON.parse(arrayraw)
notraw.push([ingredient, amount, unit]);
localStorage.setItem("Recipe", JSON.stringify(notraw));
var recipeid = notraw.length - 1
console.log("recipe id:" + recipeid)
}
//The calculation function, that gets the ingredients from the array, and calculates what ingredients are needed
function calculate(multiplier) {
alert("Calculate function was called")
var length = recipearray.length - 1;
console.log("There are " + length + " ingredients.");
for (i = 0; i < length; i++) {
console.log("raw = " + recipearray[i + 1][1] + recipearray[i + 1][2]);
console.log("multiplied = " + recipearray[i + 1][1] / recipearray[0][2] * multiplier + recipearray[i + 1][2]);
}
}
// The save function, This asks the user to input the name and how many people the recipe serves. This information is later passed onto the array.
function save() {
var verified = true;
while (verified) {
var name = prompt("What's the name of the recipe?")
var serves = prompt("How many people does it serve?")
if (serves === "" || name === "" || isNaN(serves) === true || serves === "null") {
alert("You have to enter a name, followed by the number of people it serves. Try again.")
verified = false;
} else {
alert("sucess!");
var element = document.getElementById("header");
element.innerHTML = name;
var header2 = document.getElementById("details");
header2.innerHTML = "Serves " + serves + " people"
calculate(serves)
var arrayraw = localStorage.getItem("Recipe")
var notraw = JSON.parse(arrayraw)
notraw.splice(0, 1, [name, serves, notraw.length])
localStorage.setItem("Recipe", JSON.stringify(notraw))
return;
}
}
}
// the recipe function processes the inputs for the different ingredients and amounts.
function recipe() {
// Declare all variables
var ingredient = document.getElementById("ingredient").value;
var amount = document.getElementById("number").value;
var unit = document.getElementById("unit").value;
var count = "Nothing";
console.log("Processing");
if (isNaN(amount)) {
alert("You have to enter a number in the amount field")
} else if (ingredient === "" || amount === "" || unit === "Select Unit") {
alert("You must fill in all fields.")
} else if (isNaN(ingredient) === false) {
alert("You must enter an ingredient NAME.")
} else {
console.log("hey!")
// console.log(recipearray[1][2] + recipearray[1][1])
var totalamount = amount + unit
edit(ingredient, amount, unit, false)
insRow(ingredient, totalamount) // post(0,*123456*,"Fish")
}
}
function deleteRow(specified) {
// Get the row that the delete button was clicked in, and delete it.
var inside = specified.parentNode.parentNode.rowIndex;
document.getElementById('table').deleteRow(inside);
var rowid = inside + 1 // account for the first one being 0
console.log("An ingredient was deleted by the user: " + rowid);
// Remove this from the array.
deletefromarray(-rowid);
}
function insRow(first, second) {
//var first = document.getElementById('string1').value;
//var second = document.getElementById('string2').value;
// This console.log("insRow: " + first)
// Thisconsole.log("insRow: " + second)
var x = document.getElementById('table').insertRow(0);
var y = x.insertCell(0);
var z = x.insertCell(1);
var a = x.insertCell(2);
y.innerHTML = first;
z.innerHTML = second;
a.innerHTML = '<input type="button" onclick="deleteRow(this)" value="Delete">';
}
function populateheader() {
// Populate the top fields with the name and how many it serves
var arrayraw = localStorage.getItem("Recipe")
var notraw = JSON.parse(arrayraw)
var element = document.getElementById("header");
element.innerHTML = notraw[0][0];
var header2 = document.getElementById("details");
// if statement ensures the header doesn't say '0' people, instead says no people
if (notraw[0][1] === 0) {
header2.innerHTML = "Serves no people"
} else {
header2.innerHTML = "Serves " + notraw[0][1] + " people"
}
console.log("Now populating Header, The Title was: " + notraw[0][0] + " And it served: " + notraw[0][1]);
}
function populatetable() {
console.log("Now populating the table")
// Here we're gonna populate the table with data that was in the loaded array.
var arrayraw = localStorage.getItem("Recipe")
var notraw = JSON.parse(arrayraw)
if (notraw.length === 0 || notraw.length === 1) {
console.log("Array was empty.")
} else {
var count = 1;
while (count < notraw.length) {
amount = notraw[count][1] + " " + notraw[count][2]
insRow(notraw[count][0], amount)
console.log("Inserted Ingredient: " + notraw[count][0] + notraw[count][1])
count++;
}
}
}