Javascript, variables and if/else statements - javascript

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

Related

User Prompt Array Question for Javascript

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!

count number of inputs which have value

js noob here - I'm trying to count the number of inputs that have a value out of a calculated number of them. The code I came up with trying to achieve that is the following:
var fields = document.querySelectorAll('[id^=example-]'), count = 0;
for (var z = 0; z <= fields.length; z++) {
if (fields[z].value != "") {
count = count + 1;
}
console.log('count is: ' + count);
}
Context: there are 3 inputs total and the above code executes on a click event.
Now the first time, this obviously runs fine if for example I set the value of the first input out of the three and returns [1]. The second time I update the same field's value, the counter increases again (logically).
Now, what I would like to achieve is to check all three inputs at the time the event fires & count how many of them have a value (and not increase the counter furthermore if they are already counted as having a value in the previous fire event).
Any help would be greatly appreciated. Thanks!
Shorter
const count = [...document.querySelectorAll('[id^=example-]')]
.filter(fld => fld.value.trim() !== "")
.length

innerHTML not working inside event handler function (Javascript)

I have created a function, updatePrice, which I have tied to the "click" event on the checkbox and radio buttons in my HTML form. Each checkbox and radio basically represents an item, with it's price as the value property of these <input> elements. When I check or uncheck any box, the function fires, loops through all elements in the form, and updates the total price of all the checked items into a div element I have below my form, with the id tag "priceOutput".
The following code works perfectly, printing out: The price of this item is $(price of item).
function updatePrice() {
var price = 0
for (i=0;i<=form.length;i++) {
var element = form[i]
if(element.checked) {
price+=parseInt(element.value)
}
document.getElementById("priceOutput").innerHTML = "The price of this item is $" + price + "."
}
}
But, if I switch the the last line around, the line is not printed at all:
function updatePrice() {
var price = 0
for (i=0;i<=form.length;i++) {
var element = form[i]
if(element.checked) {
price+=parseInt(element.value)
}
}
document.getElementById("priceOutput").innerHTML = "The price of this item is $" + price + "."
}
Why must I write the line in the {} of the for in order to work. Doesn't the price variable's scope extend over the entire updatePrice function?
I'm still rather new to programming, so do forgive me if this is an elementary question.
It seems to me that it isn't printing because you are causing an error. Since array indexing starts at 0 your for loop should not use <= but rather < :
for (i=0;i<form.length;i++) {
...
}
The reason why nothing gets printed then is because on the last loop the function errors and you setting the inner HTML never gets executed.
Seems like there is an error with your code, how about adding var to your for loop and removing the = from i<=form.length
for (var i = 0; i < form.length; i++)

Dynamic array using variable

I am trying to dynamically access arrays, otherwise I would have to duplicate my code, when in reality the only difference would be buildablesets1 and buildablesets2.
var buildablesets1 = [""];
var buildablesets2 = [""];
var buildablesetsx = "buildablesets" + playerturn;
for (var i = 0; i < set.length; i++) {
if (doesOwnSet('player'+playerturn, set[i])) {
if(playerturn===1) buildablesets1.push(set[i]);
}
}
if (buildablesetsx.length > 1){
var b = $("#buildsets"+playerturn);
for (k = 1; k < buildablesetsx.length; k++){
b.append("<option value='" + buildablesetsx[k]+ "'>" + buildablesetsx[k] + "</option>");
}
}
The code pushes any sets owned by the player to buildablesetsX. Then the dropdown box #buildsetsX is populated with all the owned sets.
1. How do I get the effect of buildablesetsX where X depends on the players turn.
2. I want to depopulate the dropdown box on each turn otherwise it will duplicate, since it is appending. (would apreciate a better way of doing this, ideally I want to populate the dropdown box only if there is a new set).
Plus sorry I understand that this question has been asked before, but I didnt understand the answers or the question exactly.
Any time you find yourself creating variables with sequential numbers, and wanting to access them dynamically, what you really should be using is an array. In this case, you should use a two-dimensional array:
var buildablesets = [[""], [""]];
The first dimension is the player number, the second dimension is the list of sets that player has built.
To access a particular player's sets, do:
buildablesetsx = buildablesets[playerturn];
The rest of your code will work as you've written it, with the above variable assignment.

JavaScript validation, prevent duplicate input fields

I have a form with 10 Select Lists all have the same items. The items are populated from a PHP/MySQL array. The user needs to select one item per select list. I need to prevent the user from selecting the same item twice before submitting the form.
function checkDropdowns(){
var iDropdowns = 10;
var sValue;
var aValues = new Array();
var iKey = 0;
for(var i = 1; i <= iDropdowns; ++i){
sValue = document.getElementById('test' + i).value;
if ( !inArray(sValue, aValues) ){
aValues[iKey++] = sValue;
}else{
alert('Duplicate!');
return false;
}
}
return true;
}
Use javascript to add an event listener on the value change of the selects. That function would then loop through the selects taking the values into memory after having compared it to the values it had already. If the loop finds that the current select has an option that is already selected, put it back to default value and display a little message...
Or, still on a change event, take the value of the just selected item and remove all the items of this value in the 10 selects. So at the end the user will only have 1 choice, since he only sees the options he can choose. But be careful, if the user changes his mind on one select, make sure you add back the option you removed in the first place.
Option 2 is to be prefered as a user point of view, you will cause less frustration.
EDIT:
The code you are providing already does quite a lot... All you need now is something to revert the change if it is invalid:
var defaultValues = [];
function onLoadSelect(){//Please execute this on document load, or any event when the select are made available.
var iDropdowns = 10;
var iKey = 0;
for(var i = 1; i <= iDropdowns; ++i){
var sValue = document.getElementById('test' + i).value;
defaultValues['test' + i] = sValue;
}
}
Then, in your function's else, reset the value according to the defaults we have gathered:
else{
alert('Duplicate!');
document.getElementById('test' + i).value = defaultValues['test' + i];
return false;
}
I have written code, i think it can be improved but it works as you asked.
Put it in inside script tag under body so it loads after document.
Put id names of select/dropdown elements in id array.
Take a look: //took me 3 hours O_O
http://jsfiddle.net/techsin/TK9aX/15/
i think i need better strategy to approach programming.

Categories

Resources