我有這個表格:
<form>
<div role="group" aria-labelledby="info">
<p id="info"> Datos de clientes</p>
<label class="data-label">Nombre
<input type="name" name="nombre" >
</label>
<label class="data-label">Email
<input type="email" name="email" >
</label>
<label class="data-label">Numero de personas
<input type="number" min="1" name="number" value="number">
</label>
</div>
<div role="group" aria-labelledby="destino-info">
<p id="destino-info">Destino:</p>
<label class="destino-label">
<input type="radio" name="destino" value="destino" onClick="changeFormula(1)" checked >
Cuidad</label>
<label class="destino-label">
<input type="radio" name="destino" value="manta?a" onClick="changeFormula(2)" > Monta?a </label>
<label class="destino-label">
<input type="radio" name="destino" value="playa" onClick="changeFormula(3)" >Playa</label>
<button type="submit">Calcular tarifa</button></div>
</form>
<h3>El precio:</h3>
提交時,我需要根據人數和假期型別計算總價。例如,城市的價格是 100,山 - 130,海灘 - 150。
我不明白如何根據所選單選按鈕更改成本。
這是我嘗試過的,但現在我感到迷茫:
const price =[
{cost:100},
{cost:130},
{cost:150}
];
function CalculateTotal(){
let numberOfGuests = document.getElementsByName("number").value;
let typeOfDestiny =document.getElementsByName("destino")
let total =numberOfGuests*typeOfDestiny;
}
uj5u.com熱心網友回復:
嘗試下面的代碼并將id="number" 添加到 Numero de personas欄位并將value="Cuidad" 更改為 Cuidad單選按鈕。
const priceList = [{ destination: "Cuidad", cost: 100 },{ destination: "mantana", cost: 130 },{ destination: "playa", cost: 150 },];
const TOTAL_PRICE_HEADING = 'El precio:';
function calculateTarifa() {
const slectedDestination = document.querySelector("input[name='destino']:checked").value;
const idx = priceList.findIndex((place) => place.destination === slectedDestination);
if (idx >= 0) {
const numGuests = document.getElementById("numGuests").value;
const totalCost = priceList[idx].cost * (numGuests * 1);
updateTotalCost(totalCost);
}
}
function updateTotalCost(cost) {
const totalCostElement = document.querySelector('h3');
totalCostElement.innerText = `${TOTAL_PRICE_HEADING} ${cost}`;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<form>
<div role="group" aria-labelledby="info">
<p id="info">Datos de clientes</p>
<label class="data-label">Nombre
<input type="name" name="nombre" />
</label>
<label class="data-label">Email
<input type="email" name="email" />
</label>
<label class="data-label">Numero de personas
<input type="number" min="1" id="numGuests" name="number" value="number" />
</label>
</div>
<div role="group" aria-labelledby="destino-info">
<p id="destino-info">Destino:</p>
<label class="destino-label">
<input type="radio" name="destino" value="Cuidad" checked />
Cuidad</label>
<label class="destino-label">
<input type="radio" name="destino" value="mantana" />
Monta?a
</label>
<label class="destino-label">
<input type="radio" name="destino" value="playa" />Playa</label>
<button type="button" onclick="calculateTarifa()">
Calcular tarifa
</button>
</div>
</form>
<h3>El precio:</h3>
</body>
</html>
uj5u.com熱心網友回復:
由于您的單選按鈕值是假期型別,因此您需要按該型別查找費用。您應該將price陣列更改為一個物件,以便您可以按型別查找成本。
您還可以使用貨幣格式化程式來衡量。
const form = document.forms.vacation;
const totalElement = document.querySelector('#total');
const currencyFormatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
});
const costLookup = {
'destino' : { cost: 100 },
'manta?a' : { cost: 130 },
'playa' : { cost: 150 }
};
function CalculateTotal(event) {
event.preventDefault();
const numberOfGuests = form.elements.number.value;
const typeOfDestiny = costLookup[form.elements.destino.value].cost;
const total = numberOfGuests * typeOfDestiny;
totalElement.textContent = currencyFormatter.format(total);
return false;
}
button[type="submit"] { display: block; }
.data-label { display: grid; grid-template-columns: 10em 1fr; }
#destino-info { display: inline-block; }
<form id="vacation" onSubmit="CalculateTotal(event)">
<div role="group" aria-labelledby="info">
<p id="info">Datos de clientes</p>
<label class="data-label">Nombre
<input type="name" name="nombre" >
</label>
<label class="data-label">Email
<input type="email" name="email" >
</label>
<label class="data-label">Numero de personas
<input type="number" min="1" name="number" value="number">
</label>
</div>
<div role="group" aria-labelledby="destino-info">
<p id="destino-info">Destino:</p>
<label class="destino-label">
<input type="radio" name="destino" value="destino" checked >
Cuidad
</label>
<label class="destino-label">
<input type="radio" name="destino" value="manta?a">
Monta?a
</label>
<label class="destino-label">
<input type="radio" name="destino" value="playa">
Playa
</label>
<button type="submit">Calcular tarifa</button></div>
</form>
<h3>El precio:</h3>
<div id="total"></div>
您還可以使用資料屬性,即data-cost,而不是保留價格的記憶體映射。請注意,您必須找到:checked單選按鈕才能訪問該屬性。
顯示代碼片段
const form = document.forms.vacation;
const totalElement = document.querySelector('#total');
const currencyFormatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
});
function CalculateTotal(event) {
event.preventDefault();
const numberOfGuests = form.elements.number.value;
const checked = form.querySelector('input[name="destino"]:checked');
const destinationCost = checked.getAttribute('data-cost');
const total = numberOfGuests * destinationCost;
totalElement.textContent = currencyFormatter.format(total);
return false;
}
button[type="submit"] { display: block; }
.data-label { display: grid; grid-template-columns: 10em 1fr; }
#destino-info { display: inline-block; }
<form id="vacation" onSubmit="CalculateTotal(event)">
<div role="group" aria-labelledby="info">
<p id="info">Datos de clientes</p>
<label class="data-label">Nombre
<input type="name" name="nombre" >
</label>
<label class="data-label">Email
<input type="email" name="email" >
</label>
<label class="data-label">Numero de personas
<input type="number" min="1" name="number" value="number">
</label>
</div>
<div role="group" aria-labelledby="destino-info">
<p id="destino-info">Destino:</p>
<label class="destino-label">
<input type="radio" name="destino" value="destino" data-cost="100" checked >
Cuidad
</label>
<label class="destino-label">
<input type="radio" name="destino" value="manta?a" data-cost="130">
Monta?a
</label>
<label class="destino-label">
<input type="radio" name="destino" value="playa" data-cost="150">
Playa
</label>
<button type="submit">Calcular tarifa</button></div>
</form>
<h3>El precio:</h3>
<div id="total"></div>
uj5u.com熱心網友回復:
這是另一種(希望更容易)看待它的方式。您可以將這些東西的成本作為資料集屬性直接存盤在 HTML 元素中。然后應用一個單擊偵聽器,該偵聽器將在每次單擊其中一個時計算總數。
let total = 0;
document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('[data-cost]').forEach(r => {
r.addEventListener('click', e => runCalc(e));
if (r.checked) runCalc({target: r});
})
document.querySelector('#form').addEventListener('submit', e => {
e.preventDefault(); // don't submit
let chosendest = document.querySelector('[data-cost]:checked');
console.log(`the selected destination is ${chosendest.value} for $${chosendest.dataset.cost}`);
})
})
const runCalc = e => {
let total = e.target.dataset.cost;
let loc = e.target.value
document.querySelector('#total').innerHTML = `<h2>Going to the ${loc} will cost ${total}</h2>`;
}
<form id="form">
<div role="group" aria-labelledby="destino-info">
<p id="destino-info">Destino:</p>
<label class="destino-label">
<input type="radio" name="destino" value="destino" data-cost="100" checked >
Cuidad</label>
<label class="destino-label">
<input type="radio" name="destino" value="manta?a" data-cost="120" > Monta?a </label>
<label class="destino-label">
<input type="radio" name="destino" value="playa" data-cost="130" >Playa</label>
</div>
<button type="submit">Calcular tarifa</button>
</form>
<div id='total'></div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/510117.html
標籤:javascript形式
