在总成本显示中设置默认选中的值,而不使用“值”

时间:2017-04-05 05:30:54

标签: javascript

我们可以直接将值设置为文本框中我们想要的值,例如
<input type="text" name="total" value="500" size="10" readonly />
是否有任何方法可以在文本框中显示默认选中的值,而不使用value =“500”??

var checks = document.getElementsByName('deliveryType');
for (var i = 0; i < checks.length; i++) checks[i].onclick = function() {
  var cal = document.getElementsByName('deliveryType');
  var total = 0;
  for (var i = 0; i < cal.length; i++) {
    if (cal[i].checked) {
      total += parseFloat(cal[i].getAttribute("data-price"));
    }
  }
  document.getElementsByName("total")[0].value = "$" + total.toFixed(2);
}
<form id= selectEvent>
<section id="collection">
			
			<p>
			Home - &pound;500.00 <input type="radio" name="deliveryType" value="home" data-price="500.00" checked />&nbsp; | &nbsp;
			self collect - 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>
    </form>

1 个答案:

答案 0 :(得分:1)

请尝试以下代码:

&#13;
&#13;
var checks = document.getElementsByName('deliveryType'); 
checks.forEach(function(value){
    if(value.checked){
         document.getElementsByName("total")[0].value = "$" + value.getAttribute('data-price');
    }
})
for (var i = 0; i < checks.length; i++) checks[i].onclick = function() {
  var cal = document.getElementsByName('deliveryType');
  var total = 0;
  for (var i = 0; i < cal.length; i++) {
    if (cal[i].checked) {
      total += parseFloat(cal[i].getAttribute("data-price"));
    }
  }
  document.getElementsByName("total")[0].value = "$" + total.toFixed(2);
  
}
&#13;
<form id= selectEvent>
  <section id="collection">       
      <p>
      Home - &pound;500.00 <input type="radio" name="deliveryType" value="home" data-price="500.00" checked />&nbsp; | &nbsp;
      self collect - 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>
</form>
&#13;
&#13;
&#13;