js根据输入数字计算总价并显示

时间:2021-04-12 17:46:13

标签: javascript

我有三种类型的门票。儿童 - 8 美元,退休人员 - 10 美元,成人 - 12 美元,我有 3 个输入数字,我希望这三个输入中的某个人更改以计算和打印 html 总价

这是我的html

children<input type="number" id="children" name="children" min="0" max="20" value="0" onchange="myScript">
adults<input type="number" id="adults" name="adults" min="0" max="20" value="0" onchange="myScript">
retirees<input type="number" id="retirees" name="retirees" min="0" max="20" value="0" >

这是我的js

function totalPrice(){
   var total = 0 
   var children = document.getElementsByName('children');
   var children = document.getElementsByName('adults');
   var children = document.getElementsByName('retirees');
   total = (parseInt(children) * 8) + (parseInt(adults) * 12) + (parseInt(retirees) * 10);

Here i dont know how to print in html total price

我想看起来像那样

enter image description here

4 个答案:

答案 0 :(得分:1)

一种可能的方法是在 html 中放置一个 div 来显示 Total

<div id="total"></div>

然后将 change 的“eventListener”附加到每个输入字段以触发计算

document.querySelectorAll("input").forEach(el => {
  el.addEventListener("change", () => {
    totalPrice();
  });
});

然后更新 html 中的值:

totalDiv.innerHTML = `<h3>Total: ${total}$</h3>`;

工作Stackblitz

答案 1 :(得分:0)

给定 <inputs> 下方的 div,形式为 <div id="price"></div>

您可以这样设置价格:

let price_div = document.querySelector("#price")
// Apply whatever formatting to the price you want.
price_div.innerHTML = total

答案 2 :(得分:0)

由于这些是输入字段,您可以使用它们的

function totalPrice(){
   var total = 0 
   var children = document.getElementsByName('children');
   var adults = document.getElementsByName('adults');
   var retirees = document.getElementsByName('retirees');
   total = (parseInt(children.value) * 8) + (parseInt(adults.value) * 12) + (parseInt(retirees.value) * 10);

答案 3 :(得分:0)

          function totalPrice(){
       var total = 0 
       var children = document.getElementsByName('children')[0].value;
       var adults = document.getElementsByName('adults')[0].value;
       var retirees = document.getElementsByName('retirees')[0].value;
       total = (children * 8) + (adults * 12) + (retirees * 10);
       console.log(total);
       document.getElementById('totalPrice').textContent=total;
       
       }
  children <input type="number" id="children" name="children" min="0" max="20" value="0" onKeyUp="totalPrice()">
    adults <input type="number" id="adults" name="adults" min="0" max="20" value="0" onKeyUp="totalPrice()">
    retirees <input type="number" id="retirees" name="retirees" min="0" max="20" value="0" onKeyUp="totalPrice()">
    <div id="totalPrice" style="color:red"></div>
 

相关问题