Member 13940163 Ответов: 1

Как я могу получить "квитанцию" innerhtml, чтобы добавить 3 к общему балансу, когда установлен определенный флажок?


Я прошу прощения, что следующий код длинный (я вставил все это, так как не уверен, сколько из него вам нужно увидеть, чтобы узнать, в чем проблема), но он застрял у меня на весь день.
Я следовал базовому шаблону html/js для создания формы подачи пиццы, которая вычисляет текущую сумму и детализирует каждый флажок в нижней части страницы после нажатия кнопки "Заказать".

Шаблон включал в себя выбор размера и мяса. (Я также добавил овощной раздел). Но когда дело доходит до корочки, мне нужно, чтобы общая сумма innerHTML добавила 3 дополнительных доллара к общей сумме, только если будет проверена "Сырная фаршированная корочка", чего она не делает.

I think my problem is that I don't know which parts of the meat/veg template and which parts of the size template to combine in a way that will yield the right results. Right now, I've got a mixture of the two; the "if/else" section is supposed to determine if Cheese Stuffed Crust got selected, and I also left out the "free one topping" part because it doesn't apply to that section. I'm lost on how to make this work. Would anyone mind taking a look at my code (the part labelled "Crust" is where the issue is. Thank you so much! I'd appreciate the help a lot, as I'm very frustrated at the moment. To sum up, I need 3 dollars added to the runningTotal when "Cheese Stuffed Crust" is checked. I've also included the notes that came with the original template.

Что я уже пробовал:

<!DOCTYPE html>
	<html>
	<head>
		<style>h1{text-align: center;font-size: 50pt;}
		p{font-size: 20pt; margin-left: 30px;}
		input[type="radio"] {margin-left: 30px;}
		input[type="checkbox"] {margin-left: 30px; margin-top: 20px;}
		body{background-color: yellow;}
		.float{display: inline-block;}
		.prices{font-size: 15pt;}
		button:hover{color:#000;font-weight:bold;border:2px solid#000;}
		.button {margin-left: 20px;}

</style>
</head>

	<body>

<h1>Pizza Place</h1>
	<br>
	<br>


<div class="size class">
	<p>What size pizza would you like?</p>
		<br>

<input id="btnOrder" type="button" onclick="Receipt()" 
				value="Place Order">


<form id="pizzasize"> 

			<input class="Size" type="radio" name="size"  value="Personal Pizza">Personal</input>  
			<input class="Size" type="radio" name="size"  value="Medium Pizza">Medium</input>  
			<input class="Size" type="radio" name="size" value="Large Pizza">Large</input
			>  
			<input class="Size" type="radio" name="size" value="Extra Large Pizza">Extra Large</input>

			<br>
			<br>
			<br>
			<br>
		</div>

		<div class="meat class">
		<p>Choose Meats</p>
		
<input class="Meat" type="checkbox" name="meat" value="Pepperoni">Pepperoni</input><br>
<input class="Meat" type="checkbox" name="meat" value="Sausage">Sausage</input><br>
<input class="Meat" type="checkbox" name="meat" value="Canadian Bacon">Canadian Bacon</input><br>
<input class="Meat" type="checkbox" name="meat" value="Ground Beef">Ground Beef</input><br>
<input class="Meat" type="checkbox" name="meat" value="Anchovy">Anchovy</input><br>
<input class="Meat" type="checkbox" name="meat" value="Chicken">Chicken</input><br>

</div>


<div class="veggies">
		<p>Add Veggies:</p>
		
			<input class="Veggie" type="checkbox" name="veggie" value="Tomatoes">Tomatoes<br>
<input class="Veggie"  type="checkbox" name="veggie" value="Onions">Onions<br>
<input class="Veggie" type="checkbox" name="veggie" value="Olives" checked>Olives<br>
<input class="Veggie" type="checkbox" name="veggie" value="Green Peppers">Green Peppers<br>
<input class="Veggie" type="checkbox" name="veggie" value="Mushrooms">Mushrooms<br>
<input class="Veggie" type="checkbox" name="veggie" value="Pineapple">Pineapple<br>
<input class="Veggie" type="checkbox" name="veggie" value="Spinach">Spinach<br>
<input class="Veggie" type="checkbox" name="veggie" value="Jalapeno">Jalapeno<br>


</div>

<div class="crusts">
	<p>Crust</p>
	<input class="Crust" type="radio" name="crust" value="Plain Crust">Plain Crust</input>  
			<input class="Crust" type="radio" name="crust"value="Garlic Butter Crust">Garlic Butter Crust</input>  
			<input class="Crust" type="radio" name="crust" value="Cheese Stuffed Crust">Cheese Stuffed Crust</input
			>  
			<input class="Crust" type="radio" name="crust" value="Spicy Crust">Spicy Crust</input>
			<input class="Crust" type="radio" name="crust" value="House Special Crust">House Special Crust</input>

</div>


<div id="cart">
			<div id="showText"></div>
			<div id="totalPrice"></div>
		</div>
</form>


	<script>
// Get the pizza size price and add it to the running Total
// then pass that running total to the next function so 
// the next function will add a particular total to the running total and so on...
//
// Keep doing this until you get all items added to the running total.
//
// Just remember that the syntax will be text1 = text1 + something + "<br>";
// So you take the orginal value and concetenate to something new and end it with
// an HTML line break so our code will write the next thing one line below instead
// of overwriting the previous print out.

function Receipt() {
	// This initializes our string so it can get passed from  
	// function to function, growing line by line into a full receipt
	
	var text1 = "<h3>You Ordered:</h3>";
	var runningTotal = 0;
	var sizeTotal = 0;
	var sizeArray = document.getElementsByClassName("Size");
	for (var i = 0; i < sizeArray.length; i++) {
		if (sizeArray[i].checked) {
			var selectedSize = sizeArray[i].value;
			text1 = text1+selectedSize+"<br>";
		}
	}
	if (selectedSize === "Personal Pizza") {
		sizeTotal = 6;
	} else if (selectedSize === "Medium Pizza") {
		sizeTotal = 10;
	} else if (selectedSize === "Large Pizza") {
		sizeTotal = 14;
	} else if (selectedSize === "Extra Large Pizza") {
		sizeTotal = 16;
	}
	runningTotal = sizeTotal;
	console.log(selectedSize+" = $"+sizeTotal+".00");
	console.log("size text1: "+text1);
	console.log("subtotal: $"+runningTotal+".00");
	getMeat(runningTotal,text1); // All three of these variables will be passed on to each function
};	

// With both the meat and veggie functions each item in the array will be
// 1 dollar but the first is going to be free so we can count the total
// of items in their array and subtract 1 to get the total item cost
//
// Now we can add the item cost to our running total to get the new
// running total and then pass this new running total to the next function
// Just keep up this process until we've added all items to the running total
function getMeat(runningTotal,text1) {
	var meatTotal = 0;
	var selectedMeat = [];
	var meatArray = document.getElementsByClassName("Meat");
	for (var j = 0; j < meatArray.length; j++) {
		if (meatArray[j].checked) {
			selectedMeat.push(meatArray[j].value);
			console.log("selected meat item: ("+meatArray[j].value+")");
			text1 = text1+meatArray[j].value+"<br>";
		}
	}
	var meatCount = selectedMeat.length;
	if (meatCount > 1) {
		meatTotal = (meatCount - 1);
	} else {
		meatTotal = 0;
	}
	runningTotal = (runningTotal + meatTotal);
	console.log("total selected meat items: "+meatCount);
	console.log(meatCount+" meat - 1 free meat = "+"$"+meatTotal+".00");
	console.log("meat text1: "+text1);
	console.log("Purchase Total: "+"$"+runningTotal+".00");
	getVeg(runningTotal,text1); 


};	


function getVeg(runningTotal,text1) {
	var vegTotal = 0;
	var selectedVeg = [];
	var vegArray = document.getElementsByClassName("Veggie");
	for (var j = 0; j < vegArray.length; j++) {
		if (vegArray[j].checked) {
			selectedVeg.push(vegArray[j].value);
			console.log("selected veg item: ("+vegArray[j].value+")");
			text1 = text1+vegArray[j].value+"<br>";
		}
	}
	var vegCount = selectedVeg.length;
	if (vegCount > 1) {
		vegTotal = (vegCount - 1);
	} else {
		vegTotal = 0;
	}
	runningTotal = (runningTotal+vegTotal);
	console.log("total selected veg items: "+vegCount);
	console.log(vegCount+" veg - 1 free veg = "+"$"+vegTotal+".00");
	console.log("veg text1: "+text1);
	console.log("Purchase Total: "+"$"+runningTotal+".00");
	getCrust(runningTotal,text1); 

	
};

//CRUST


//Here's where I'm having trouble. I can't get the inner html to add 3 dollars for cheese crust. (crustTotal should equal 3 if "Cheese Filled Crust" checkbox is checked, and 3 should therefore be added to the runningTotal.)


function getCrust(runningTotal,text1) {
	var selectedCrust = [];
	var crustTotal = 0;
    
	var crustArray = document.getElementsByClassName("Crust");
	for (var i = 0; i < crustArray.length; i++) {
		if (crustArray[i].checked) {

				if (crustArray[i].checked) {
		var selectedCrust = crustArray[i].value;
		}
	}
			
	if (selectedCrust === "Cheese Stuffed Crust") {
		crustTotal=3;
	}  else if (selectedCrust === "Plain Crust") {
        crustTotal=0;
    }  else if (selectedCrust === "Garlic Butter Crust") {
        crustTotal=0;
    }  else if (selectedCrust === "Spicy Crust") {
        crustTotal=0;
    } else if (selectedCrust==="House Special Crust") {
    	crustTotal=0;
	}
	runningTotal = (runningTotal+crustTotal);

	console.log(selectedCrust+" = $"+crustTotal+".00");
	console.log("crust text1: "+text1);
	console.log("Purchase Total: "+"$"+runningTotal+".00");
	document.getElementById("showText").innerHTML=text1;
	document.getElementById("totalPrice").innerHTML = "<h3>Total: $"+runningTotal+".00"+"</h3>";
};
    
    //END CRUST

	</script>
	 
	

</body>
</html>

1 Ответов

Рейтинг:
0

Bryian Tan

Основываясь на том, что было опубликовано здесь. Похоже, что в приведенных ниже кодах отсутствует символ"}", а переменная selectedCrust должна находиться вне цикла

for (var i = 0; i < crustArray.length; i++) {
		if (crustArray[i].checked) {

				if (crustArray[i].checked) {
		var selectedCrust = crustArray[i].value;
		}
	}


Код должен выглядеть так:
var selectedCrust;
var crustArray = document.getElementsByClassName("Crust");
for (var i = 0; i < crustArray.length; i++) {
    if (crustArray[i].checked) {

        if (crustArray[i].checked) {
            selectedCrust = crustArray[i].value;
        }
    }
}


Пример: cp_pizza - JSFiddle[^]

Есть также проблема тегов с HTML-разметкой. Например, </input> не является допустимым закрывающим тегом.


Member 13940163

Спасибо! Это все исправило!! И я починю бирку. Спасибо за помощь!

Bryian Tan

В любое время.