JavaScript动态计算价格并显示到HTML输入框

JavaScript动态计算价格并显示到HTML输入框

本教程旨在解决如何将JavaScript动态计算出的价格从一个HTML div元素同步显示到一个input文本框的问题。通过在HTML中添加一个input元素并修改JavaScript的calculateTotal函数,我们可以确保用户在选择不同选项时,最终价格不仅显示在div中,也能实时更新到可提交的input字段,从而提升表单数据的完整性和用户体验。

概述

在web开发中,经常需要根据用户的选择动态计算总价或其他数值。原始代码已经实现了将计算结果显示在一个div元素中。然而,在某些场景下,例如表单提交,我们可能需要将这个动态计算的值放入一个input标签中,以便随表单一起提交或进行其他操作。本教程将详细介绍如何实现这一功能。

核心问题与解决方案

原始代码中的calculateTotal函数负责计算蛋糕的总价,并将其内容更新到ID为totalPrice的div元素中。为了将此价格也显示在input标签中,我们需要:

  1. 在HTML中添加一个input标签,用于显示价格。
  2. 修改calculateTotal JavaScript函数,使其在计算出价格后,除了更新div的内容外,也更新新添加的input标签的value属性。

实现步骤

1. HTML结构调整

首先,在现有的HTML表单中,找到div id=”totalPrice”元素的位置,并在其下方或适当位置添加一个类型为text的input标签。为了方便JavaScript访问,给这个input标签一个唯一的id,例如displayPrice。

<div id="totalPrice" style="background:red;"></div> <!-- 新增的用于显示价格的输入框 --> <input type="text" id="displayPrice" readonly>

这里,我们添加了readonly属性,因为这个input主要用于显示计算结果,不希望用户手动修改。如果需要用户可编辑,可以移除此属性。

2. JavaScript函数修改

接下来,需要修改calculateTotal函数。在该函数中,已经计算出了cakePrice,并且通过document.getElementById(‘totalPrice’).innerHTML更新了div的内容。我们只需增加一行代码,通过document.getElementById(‘displayPrice’).value来更新新input标签的值。

立即学习Java免费学习笔记(深入)”;

找到calculateTotal函数:

JavaScript动态计算价格并显示到HTML输入框

viable

基于GPT-4的AI非结构化数据分析平台

JavaScript动态计算价格并显示到HTML输入框100

查看详情 JavaScript动态计算价格并显示到HTML输入框

function calculateTotal() {   // ... 其他计算逻辑 ...   var cakePrice = getCakeSizePrice() + getFillingPrice() + candlesPrice() + insciptionPrice() + tenAnchorPrice * getAnchorQuantity();    var divobj = document.getElementById('totalPrice');   divobj.style.display = 'block';   divobj.innerHTML = "Total Price for the Cake $" + cakePrice;    // 新增代码:将计算出的价格赋给input标签   var displayTotal = document.getElementById('displayPrice');   displayTotal.value = "$" + cakePrice; // 注意这里也加上了货符号 }

修改后的calculateTotal函数会同时更新div和input元素。

完整示例代码

以下是整合了HTML和JavaScript修改后的完整代码。

HTML部分

<html lang="en"> <head>     <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> <body translate="no" onload='hideTotal()'>   <div id="wrap">     <form action="" id="cakeform">         <div class="cont_order">             <fieldset>                 <legend>Anchor price</legend>                  <label for="">Size of the cake</label> <br>                 <label for="" class="radiolabel">                     <input type="radio" name="selectedcake" value="Round6" onclick="calculateTotal() ">Round cake 6"- service 8 people ($20)                 </label>  <br>                 <label for="" class="radiolabel">                     <input type="radio" name="selectedcake" value="Round8" onclick="calculateTotal()"> Round cake 8" - service 12 people ($25)                 </label> <br>                 <label for="" class="radiolabel">                     <input type="radio" name="selectedcake" value="Round10" onclick="calculateTotal()"> Round cake 10" - service 16 people ($35)                 </label> <br>                 <label for="" class="radiolabel">                     <input type="radio" name="selectedcake" value="Round12" onclick="calculateTotal()"> Round cake 12" - service 30 people ($75)                 </label> <br>                  <br>                 <label for="">Filling</label>                  <select name="filling" id="filling" onchange="calculateTotal()">                     <option value="None"> Select Filling</option>                     <option value="Lemon">Lemon($5)</option>                     <option value="Custed">Custed($5)</option>                     <option value="Fudge">Fudge($7)</option>                     <option value="Mocha">Mocha($8)</option>                 </select>  <br>  <br>                  <label for="">Anchor price: Tk 4.50 </label>                 <select name="quantity" id="quantity" onchange="calculateTotal()">                     <option value="0">Qnty</option>                     <option value="1">1</option>                     <option value="2">2</option>                     <option value="3">3</option>                     <option value="4">4</option>                     <option value="5">5</option>                     <option value="6">6</option>                     <option value="7">7</option>                     <option value="8">8</option>                     <option value="9">9</option>                     <option value="10">10</option>                 </select>                 <br>                  <p>                     <label for="includecandles" class="inlinelabel"> Include Candles ($5)</label>                     <input type="checkbox" id="includecandles" name="includecandles" onclick="calculateTotal()"/>                 </p>                  <p>                     <label for="includeinscription">Include Inscription($20)</label>                     <input type="checkbox" id="includeinscription" name="includeinscription" onclick="calculateTotal()">                 </p>                 <div id="totalPrice" style="background:red;"></div>                 <!-- 新增的用于显示价格的输入框 -->                 <input type="text" id="displayPrice" readonly>              </fieldset>         </div>         <input type="submit" id="submit" value="Submit" onclick="calculateTotal()" style="margin-top: 5px;">     </form> </div> </body> </html>

JavaScript部分

var cake_prices = new Array(); cake_prices["Round6"] = 20; cake_prices["Round8"] = 25; cake_prices["Round10"] = 35; cake_prices["Round12"] = 75;  var filling_prices = new Array(); filling_prices["None"] = 0; filling_prices["Lemon"] = 5; filling_prices["Custed"] = 5; filling_prices["Fudge"] = 7.9; filling_prices["Mocha"] = 8;  var tenAnchorPrice = 4.50; var Anchor_Quantity = new Array(); Anchor_Quantity["0"] = 0; Anchor_Quantity["1"] = 1; Anchor_Quantity["2"] = 2; Anchor_Quantity["3"] = 3; Anchor_Quantity["4"] = 4; Anchor_Quantity["5"] = 5; Anchor_Quantity["6"] = 6; Anchor_Quantity["7"] = 7; Anchor_Quantity["8"] = 8; Anchor_Quantity["9"] = 9; Anchor_Quantity["10"] = 10;  function getCakeSizePrice() {   var cakeSizePrice = 0;   var theForm = document.forms["cakeform"];   var selectedCake = theForm.elements["selectedcake"];   for (var i = 0; i < selectedCake.length; i++) {     if (selectedCake[i].checked) {       cakeSizePrice = cake_prices[selectedCake[i].value];       break;     }   }   return cakeSizePrice; }  function getFillingPrice() {   var cakeFillingPrice = 0;   var theForm = document.forms["cakeform"];   var selectedFilling = theForm.elements["filling"];   cakeFillingPrice = filling_prices[selectedFilling.value];   return cakeFillingPrice; }  function getAnchorQuantity() {   var AnchorQuantity = 0;   var theForm = document.forms["cakeform"];   var selectedAnchor = theForm.elements["quantity"];   AnchorQuantity = Anchor_Quantity[selectedAnchor.value];   return AnchorQuantity; }  function candlesPrice() {   var candlePrice = 0;   var theForm = document.forms["cakeform"];   var includeCandles = theForm.elements["includecandles"];   if (includeCandles.checked == true) {     candlePrice = 5;   };   return candlePrice; }  function insciptionPrice() {   var inscriptionPrice = 0;   var theForm = document.forms["cakeform"];   var includeInscription = theForm.elements["includeinscription"];   if (includeInscription.checked == true) {     inscriptionPrice = 20;   };   return inscriptionPrice; }  function calculateTotal() {   var cakePrice = getCakeSizePrice() + getFillingPrice() + candlesPrice() + insciptionPrice() + tenAnchorPrice * getAnchorQuantity();    var divobj = document.getElementById('totalPrice');   // 获取新添加的input元素   var displayTotalInput = document.getElementById('displayPrice');     divobj.style.display = 'block';   divobj.innerHTML = "Total Price for the Cake $" + cakePrice;    // 更新input元素的值   displayTotalInput.value = "$" + cakePrice;  }  function hideTotal() {   var divobj = document.getElementById('totalPrice');   divobj.style.display = 'none';   // 页面加载时也隐藏或清空input的值   var displayTotalInput = document.getElementById('displayPrice');   if (displayTotalInput) {       displayTotalInput.value = "";    } }

注意事项

  • ID的唯一性: 确保HTML中的id属性是唯一的,这样JavaScript才能准确地获取到目标元素。
  • 数据类型: 在将数字值赋给input的value属性时,它会被自动转换为字符串。如果后续需要对这个值进行数学运算,需要使用parseFloat()或parseInt()将其转换回数字。
  • 用户体验: 考虑到input标签通常用于用户输入,如果只是显示,可以考虑添加readonly属性或disabled属性,防止用户误操作。readonly允许值被复制但不能编辑,disabled则完全禁用并阻止提交。
  • 初始化: 在hideTotal函数中,除了隐藏div,也可以考虑清空或隐藏新添加的input标签的值,以保持初始状态的一致性。
  • 事件监听: 在更现代的JavaScript开发中,推荐使用addEventListener来绑定事件,而不是直接在HTML中使用onclick、onchange等内联事件处理。这有助于分离HTML和JavaScript代码,提高可维护性。

总结

通过在HTML中引入一个具有特定ID的input标签,并在JavaScript的动态计算函数中,通过document.getElementById().value来更新该input标签的值,我们成功地将动态计算出的价格从div同步显示到了input字段。这一方法简单有效,能够满足在表单中收集动态计算结果的需求,提升了Web应用的交互性和数据处理能力。

javascript java jquery html js ajax cdn html表单 表单提交 JavaScript html 数据类型 字符串 事件 innerHTML input

上一篇
下一篇