簡體   English   中英

如何根據所選單選按鈕計算總價

[英]How to calculate total price depending on the selected radio button

我有這個表格:

<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;
}

由於您的單選按鈕值是假期類型,因此您需要按該類型查找費用。 您應該將price數組更改為 object,以便您可以按類型查找成本。

您還可以加入貨幣格式化程序以備不時之需。

 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>

嘗試下面的代碼並將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>

這是另一種(希望更簡單)的查看方式。 您可以將這些東西的成本作為數據集屬性直接存儲在 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM