EDIT: Thanks to someone's response, I got a portion working. It now adds topping prices no problem. However, it adds a price even when a user doesn't put toppings into the prompt. I've updated my code below.
EDIT 2: For full code, here's my github link. It's updated with the below code (and the rest of the coding) https://github.com/cas389/m4-hw6-ju-cheryl.
I'm in a JavaScript class, and I am stuck on this portion of my homework assignment. Basically, we are creating a pizza ordering system where a user would fill out if they want thin/thick/pan crust, which toppings they want, if they want extra cheese and finally if they want delivery.
I have everything except the pizza toppings part. This is the information for this section (including the comments the teacher gave us as "hints") along with what I've been trying to make work. I've cut out all the sections I've already finished.
function getPizzaOrder() {
var extraCheeseUpcharge = 1.5
var thickCrustUpcharge = 2
var deliveryFee = 3.5
var toppingsFee = 1.5
var basePrice = 10
var toppings = prompt("Please enter additional toppings (comma separated)")
// HINT: prompt() will return an empty string "" if the user presses 'OK' without entering a value
// if the user enters toppings, use .split(",") to separate toppings into an array
// if no toppings are given, make sure pizza.toppings is set to []
// if the user has added toppings, add toppingsFee multiplied by
// the number of toppings added to pizza.cost
// YOUR CODE HERE
pizza.toppings = [];
pizza.toppings = toppings.split(',');
for (let i = 0; i < pizza.toppings.length; i++){
pizza.cost += toppingsFee;
}
console.log(pizza.toppings);
return pizza
}
Access element through index. And first of all You should declare pizza
let pizza;
pizza.toppings = [];
pizza.toppings = toppings.split(',');
for (let i = 0; i < pizza.toppings.length; i++){
pizza.cost += +pizza.toppings[i] * toppingsFee;
}
I figured it out with some help of the comments. I needed to create an if / else statement around my for statement :) I got it to work now!
Related
For context, just starting with JS, and wanted to do something simple, create a Higher/Lower guessing game. I have it fully working, though I wanted to add some more color to it, so my idea is to create a list of previously guessed numbers and whether that number is higher or lower than the target number (the number that they have to guess). though I currently have it set up where
const guesses = document.querySelector(".guesses");
and
guesses.textContent += userGuess + ' ';
so it just creates this extremely long, sentence-like line of previously guessed numbers that is in all white. Is there any way for me to change it so that each individual guess can somehow be listed and can be either red or green depending on if the target number is higher or lower?
For the if, else, and else if statements, I just have it so that it shows a certain text stating if the guess is too high or too low, and if it's exact, then it gives the option to restart the game
Edit, more parts of the code:
js:
let userGuess = guessField.valueAsNumber
const guessField = document.getElementById('guessField');
guessField is just an input tag in HTML
then in js, I have it generate some number, save that as randomNumber with let randomNumber = Math.floor(Math.random() * 100 + 1)
then if userGuess === randomNumber then show a p tag saying that it's right, and give it a green background or else say it's wrong (that p tag). Then I have it look if the userGuess number is lower or higher than the target number (aka the randomNumber) if it's too high, show a paragraph saying it's too high, and if it's too low, show a paragraph saying it's too low.
Add guesses in a list instead of just as text in a div. Add backgroundColor style to the result p tag to show whether guess is higher or lower or correct.
let randomNumber = Math.floor(Math.random() * 10 + 1)
const guesses = document.querySelector("#guesses");
const result = document.querySelector("#result");
function checkNum() {
let guessField = document.getElementById('guessField');
let userGuess = parseInt(guessField.valueAsNumber, 10);
var node = document.createElement("li");
var textnode = document.createTextNode(userGuess);
node.appendChild(textnode);
guesses.appendChild(node);
guessField.value = "";
result.style.backgroundColor = "tomato";
if (userGuess === randomNumber) {
result.style.backgroundColor = "aquamarine";
result.innerHTML = "You are right";
} else if (userGuess < randomNumber) {
result.innerHTML = "Guess is lower";
} else {
result.innerHTML = "Guess is higher";
}
}
p {
font-weight: bold;
}
<ul id="guesses">
</ul>
<input type="number" id="guessField" />
<button onclick="checkNum()">check</button>
<p id="result"></p>
We have very minimal info here on what you would like to accomplish and the code you are using however I think we'll be able to help you out here :)
there are a few approaches you can take here, I'm not sure if you're using any databases for your use case but since you're starting off I'm going to assume you simply want to store the values submitted via the input field in an array and later iterate through the array in an effort to pull values from it and perform operations with each iteration.
first you would need to declare an array:
const guessedNumbers = [];
next to store the values from user input you would need to to create a submit event listener on your form that will invoke a function to store the value user submits in the guessedNumbers array. In order to store the values in the guessedNumbers array you can use the .push method:
form = document.querySelector('your-form-selector');
form.addEventListener('submit', (e) => {
const userInputValue = document.querySelector('your-input-field-selector').value;
guessedNumbers.push(userInputValue);
});
Now if you need to access the values stored in the guessedNumbers array, there are multiple built in methods that allow you to accomplish this. Have a look at this MDN link that will shed some light on these array methods. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
for example you may want to iterate through each value in the array and console.log each iteration's value:
guessedNumbers.forEach((number) => console.log(number))
Happy coding!
I wrote JavaScript code which tells you the average of numbers. You enter the numbers by pressing the add button. The added numbers will be shown on the screen. If you don't enter any number, A text "empty string" will be shown and if you enter numbers this message will be not shown and the average of entered numbers will be shown.
But the problem is that, even after entering the numbers still the text "empty string" is shown. And I can't find out why. When I wrote this code without giving user the ability to enter numbers and provide numbers by myself. The same code was working correctly and was showing average but when I added the function to enter numbers... the "average code" start troubling.
Code:
<body>
<h2>Averge Function</h2>
<p>Press the button below to add numbers in the array:<br>
<button onclick="addNum()">Add</button>
</p>
<p id="numInArray"></p>
<p id="average"></p>
<!--JS Code-->
<script>
var grades = [];
function addNum() {
var grade = prompt("Add a number");
grades[grades.length] = grade;
document.getElementById("numInArray"). innerHTML =
"Numbers in array are: " + grades;
}
var sum = 0;
if (grades.length > 0) {
for (index = 0; index < grades.length; index++) {
sum += grades[index];
}
document.getElementById("average").innerHTML = sum/grades.length;
}
else {
document.getElementById("average").innerHTML = "Empty string";
}
</script>
</body>
Among things you should look into
When code is executed (function declaration, vs execution
The order of things
Scopes
An example of how you could rewrite your code with some comments on what has been changed:
<body>
<h2>Averge Function</h2>
<p>
Press the button below to add numbers in the array:<br />
<button onclick="addNum()">Add</button>
</p>
<p id="numInArray"></p>
<p id="average"></p>
<!--JS Code-->
<script>
// Initiate application by declaring variables that should be re-used for everytime addNum will be executed
var grades = [];
var sum = 0;
// Initiate the DOM, changed "Empty string" to "Empty array" while I am nitpicking anyways ;)
document.getElementById("average").innerHTML = "Empty array";
// Function that runs only when user creates an input
function addNum() {
var grade = prompt("Add a number");
// Push is a simple way to add something to an array (in this case grade to your grades array)
grades.push(grade);
// Removed that for loop for there was no use....
// Add the grade value (still available from the prompt above) to your sum variable and force it to be a number with parseInt! (If you don't force the prompt value to be a number javascript will take your initial sum 0 and add a string of the user input e.g. "5", javascript will convert that into "05", add another 5 and javascript will store "055", giving some unexpected results)
sum += parseInt(grade);
// Update the DOM
document.getElementById("numInArray").innerHTML = "Numbers in array are: " + grades;
document.getElementById("average").innerHTML = sum / grades.length;
}
</script>
</body>
Final tip from me would be:
First "design" your application in pseudo code, trying to explain what will need to happen in detail in every step. In this case steps I would identify would be:
Initialization of the app
Updates after user input
When you are calling the addNum() function, you are simply adding more elements to your array, and not much else. What you need to do is, add the numbers in addNum() again and putting that in the HTML. I've refactored your code. A few pointers:
Avoid using var, and instead use const and let, as they help you manage scope of your variable more easily.
To add more items to an array use, Array.push().
I've wrapped your static string Numbers in array are: in a <p> element that in turn has the <p> element to display your numbers.
If try to add a string and number in JavaScript, they will simply be concatenated together. Use parseInt() to get the integer value of a variable. This returns NaN when the the first non-whitespace character cannot be converted to a number.
const grades = [];
function addNum() {
const grade = prompt("Add a number");
if(grade.length > 0){
grades.push(grade);
}
document.getElementById("numInArray").textContent = grades;
document.getElementById("average").textContent = findSum();
}
function findSum() {
let sum = 0;
for (index = 0; index < grades.length; index++) {
sum += parseInt(grades[index]);
}
return sum > 0 ? sum / grades.length : "Empty string";
}
<h2>Averge Function</h2>
<p>Press the button below to add numbers in the array:<br>
<button onclick="addNum()">Add</button>
</p>
<p>Numbers in array are: <span id="numInArray"></span></p>
<p id="average"></p>
Trying to teach myself javascript I can do some minor scripts by myself but this one has got me stumped. I have been trying for weeks and cant get anywhere.example image
MY goal is to have the field labeled end item automatically populate with the last item filled in on the list.
I know how to do this in excel but with javascript I am completely lost any guidance would be greatly appreciated thanks in advance.
I have tried this before:
var one = this.getField("a1");
var two = this.getField("a2");
var three = this.getField("a3");
//for all 25 fields
if(two.value==''||two.value==null){
this.getField("a1")}
else if (three.value==''||three.value==null){
this.getField("a2")}
//for all 25 fields
The loop shown below loops over all of your fields. As long as it finds a value, it remembers that value (so "theResult" always contains the currently last found item). If no value is found (in other words, if we find the last item in the list, we simply break and know that "theResult" contains the last real value.
// Start by not having any result
var theResult = null;
// Loop over all fields
for (var theIndex = 1; theIndex < 26; theIndex++) {
// get this field
var theField = this.getField( "a" + theIndex );
// If this field has a value, take it, if not quit our loop
if (theField.value) {
theResult = theField.value;
} else {
break;
}
}
I'm a complete Javascript newbie and I'm helping my friend with a small project for college.
The idea is that when a checkbox is checked an item is chosen, and then when a "total" button is pressed, the sum of the checked items is printed. I've been using if/else statements so if checked var staticprice = 29.00 and else var staticprice = 0.00, which appears to work fine until I total it. Adding the variable "staticprice" always returns a value of 0.00, even when checked.
It's very messy (as is my first attempt creating something like this): http://jsfiddle.net/mNmQs/180/
What am I missing here?
Cheers
Couple of things to make life easier, give your checkboxes a value, that is what it's there for! I've updated your fiddle to include the appropriate values per checkbox. The next is loops, simply loop your checkboxes, if checked, add the value of the checked input to the total:
var totalBtn = document.getElementById("total"),
checkboxes = document.getElementsByTagName("input");
totalBtn.onclick = function() {
var total = 0;
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
total = total + parseInt(checkboxes[i].value);
}
}
alert(total);
}
http://jsfiddle.net/mNmQs/181/
You could change this line:
this.grandTotal= +seaprice + +stillprice + +staticprice;
To:
grandTotal= parseInt(seaprice,10) + parseInt(stillprice,10) + parseInt(staticprice,10);
In this case the problem is that you're trying to sum strings instead of numbers
JSFiddle example
HOWEVER it seems in this case there's no point in declaring your prices as strings. Of course unless you wanted to show the prices with in the format 0.00, otherwise just declare them as numbers and that should be better, like: var seaprice = 39.00; or var seaprice = 39.00; instead of var seaprice = "39.00";
Other fiddle
I know the question about obtaining a random number with javascript (non repeating) is often asked but in my case I append the same jquery code twice or three time and I would like to obtain different information each time.
First i have a large array (150 items) which is built this way :
var arr = [
{
"Numéro": "1",
"Chinois": "爱",
"Pinyin": "ài",
"Français": "aimer, affection, apprécier",
"Classificateurs": ""
},
Then I found on another post this random function :
while(arr.length < 150){
var randomnumber=Math.ceil(Math.random()*147)
var found=false;
for(var i=0;i<arr.length;i++){
if(arr[i]==randomnumber){found=true;break}
}
if(!found)arr[arr.length]=randomnumber;
}
Then I append the array information (I tried randomly - It's a flashcard kind of page so on click, the next "index" should be randomized and unique) on the page :
$('#qcm-az, .suivantQcm1').on ('click', function(qcmaz){
$('#reponse1').html(arr[index].Français);
$('#reponse2').html(arr[147 -Math.floor((Math.random() * 23)+1)].Français);
$('#reponse3').html(arr[99 - Math.floor((Math.random() * 65)+1)].Français);
$('#reponse4').html(arr[43 - Math.floor((Math.random() * 21)+1)].Français);
index = randomnumber;
});
So basically on page load or (if the next arrow is clicked) I would like the "index = randomnumber" to be ran once again but it seems stuck (because the random number seems allocated once and for all).
Finally you can see that, on my different divs, I'm using a not so random function to get a different index number. I often encounter a problem which is that the "good answer" (reponse1) is the same as in one of the "wrong answer" (reponse2,3 or 4).
I hope I explained myself clearly - I'm beginning in Javascript/Jquery. Thank you in advance.
Edit : I added a fiddle to show you the problem (just click on the body to move to next item - which is stuck after one click here)
http://jsfiddle.net/Hv8SD/
You array-shuffling algorithm is fully incorrect.
A can propose this variant:
var counter = 0, newArray = [];
while(counter < 147)
{
var randomnumber=Math.ceil(Math.random()*147 - 1)
if(!newArray[randomnumber]) // if newArray doesn't contains index `randomnumber`
{
newArray[randomnumber]=arr[counter];
counter++;
};
};
JSFiddle DEMO