我如何通过一个对象数组运行一个简单的循环,以检查先前从表单中提取的值的相似性。我正在做一个项目,其中我正在建立一个比萨饼店。用户将在表单中输入所需的比萨饼大小和浇头。然后我将提取total的值。
这是我用来从表单中提取值的JavaScript代码:
let form=document.querySelector("form");
form.addEventListener("submit",(event)=>{
event.preventDefault();
// run an array through the checkbox
let topping=[];
document.querySelectorAll('[type="checkbox"]').forEach(item=>{
if (item.checked=== true)
{
topping.push(item.value);
}})
let pizzaSze=[
{size: "8 inch",cost: 8},
{size: "10 inch", cost:10},
{size: "12 inch", cost:12},
{size:"14 inch", cost:14},
];
let top=[
{type:"sausage", cost:1},
{type:"pepperoni", cost:1},
{type:"ham", cost:1},
{type:"chicken", cost:1},
{type:"onions", cost:1},
{type:"greenpeppers", cost:1},
];
//to extract the value of the text field:
let fullname=document.querySelector("#fullname").value;
let address=document.querySelector("#address").value;
let pies=document.querySelector("#pies").value;
let
pizzasize=document.querySelector('input [name=“size”]:checked').value;
下面是HTML:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Pizza Assignment</title>
</head>
<body>
<h>Pizza Perfect</h>
<br/><br/>
<form>
<label for="fullname">Please Enter Your First Name:</label>
<input type="text" required id="fullname" size="20"
name="fullname">
<br/> <br/>
<label for="address">Please Enter Your Address:</label>
<input type="text" required id="address" size="20"
name="address">
<br/> <br/>
<label for="pies">Please Enter Number Of Pies:</label>
<input type="number" required id="pies" size="20"
name="pies">
<br/><br/>
<p>Please Enter Size:</p>
<input type="radio" id="8 inch" name="size" value="8 inch">
<label for="8 inch">8 inch</label>
<br/>
<input type="radio" id="10 inch" name="size" value="10 inch">
<label for="10 inch">10 inch</label>
<br/>
<input type="radio" id="12 inch" name="size" value="12 inch">
<label for="12 inch">12 inch</label>
<br/>
<input type="radio" id="14 inch" name="size" value="14 inch">
<label for="14 inch">14 inch</label>
<br/><br/>
<p>Toppings:</p>
<input type="checkbox" id="pepperoni" name="topping"
value="pepperoni">
<label for="pepperoni">Pepperoni</label>
<br/>
<input type="checkbox" id="sausage" name="topping"
value="sausage">
<label for="sausage">Sausage</label>
<br/>
<input type="checkbox" id="ham" name="topping" value="ham">
<label for="ham">Ham</label>
<br/>
<input type="checkbox" id="chicken" name="topping"
value="chicken">
<label for="chicken">Chicken</label>
<br/>
<input type="checkbox" id="onions" name="topping"
value="onions">
<label for="onions">Onions</label>
<br/>
<input type="checkbox" id="greenpeppers" name="topping"
value="greenpeppers">
<label for="greenpeppers">Green Peppers</label>
<br/><br/>
<button type="submit">Submit Order</button>
<button type="reset">Reset</button>
</form>
2条答案
按热度按时间6l7fqoea1#
你试过使用
for
循环吗?例如:
这允许您循环遍历数组中的所有项目,并根据浇头确定您的总价。
daupos2t2#
可以使用
for
或forEach
循环:for
:forEach
:你使用的是一个关联数组,其中每个键对应一个值,所以,为了访问你需要的值,你只需要在括号中指明你的键。然后你只需要在循环中进行你需要的计算。