在总计框中显示单选按钮计算吗?

时间:2019-12-30 20:00:14

标签: javascript html

如果用户单击数据价格为5.99的单选按钮,那么价格将显示在总计框中,但是如果用户单击“不收费”单选按钮,则不会显示任何内容

var radio = document.querySelector("input[name=deliveryType]");
for (var i = 0; i < radio.length; i++) {

  if (radio.checked) {
    l_totalPrice += parseFloat(radio.dataset.price);
  }
}
total.value = l_totalPrice;
<section id="collection">
  <h2>Collection method</h2>
  <p>Please select whether you want your chosen event ticket(s) to be delivered to your home address (a charge applies for this) or whether you want to collect them yourself.</p>
  <p>
    Home address - &pound;5.99 <input type="radio" name="deliveryType" value="home" data-price="5.99" checked>&nbsp; | &nbsp; Collect from ticket office - no charge <input type="radio" name="deliveryType" value="ticketOffice" data-price="0">
  </p>
</section>

<section id="checkCost">
  <h2>Total cost</h2>
  Total <input type="text" name="total" size="10" readonly>
</section>

2 个答案:

答案 0 :(得分:1)

使用event delegationdataset API,这很容易:

let total = document.querySelector("input[name='total']");

// Set the event listener up on an ancestor of both radio buttons
document.getElementById("collection").addEventListener("click", function(event){
  // When the event is triggered here, check the event.target to see what element
  // actually triggered the event. 
  if(event.target.value === "home"){
    // Use the dataset API to access the data-* attribute.
    total.value = event.target.dataset.price;
  } else {
    total.value = "";
  }
  
});
#collection h1, #checkCost h1 { font-size:1.9em; }
<section id="collection">
  <h1>Collection method</h1>
  <p>Please select whether you want your chosen event ticket(s) to be delivered to your home address (a charge applies for this) or whether you want to collect them yourself.</p>
  <p>
    Home address - &pound;5.99 
    <input type="radio" name="deliveryType" value="home" data-price="5.99" checked>&nbsp; | &nbsp; 
    Collect from ticket office - no charge 
    <input type="radio" name="deliveryType" value="ticketOffice" data-price="0">
  </p>
</section>

<section id="checkCost">
  <h1>Total cost</h1>
  Total <input type="text" name="total" size="10" readonly>
</section>

仅供参考:一节中的第一个标题元素应始终为h1。如果您不想要该字体大小,只需使用CSS对其进行修改。切勿使用HTML元素,因为浏览器将采用默认样式。

答案 1 :(得分:0)

你在这里

function updateTotal(ele) {
	document.getElementById("total").value = ele.value;
}
<input type="radio" id="home" value="5.99" name="delivery_type" onchange="updateTotal(this)"/> 
<label for="home">Home address - <b>&pound;5.99</b></label>
<br>
<input type="radio" id="office" value="0" name="delivery_type" onchange="updateTotal(this)"/> 
<label for="office">Collect from ticket office - <b>no charge</b></label>
<br>
<br>
<input type="number" id="total" name="total" placeholder="Choose a delivery address" readonly/>


让我知道您是否有任何困惑:)