用Javascript从带有输入标题的单选按钮中获取金额



我有点拘泥于此,因为我可以在这里找到许多示例代码,它们从带有id或value的无线电输入中获取值。

如何只使用纯javascript从下面的标题中获得它,然后输出到total?

<p>
    Home address - &pound;4.99 <input type="radio" name="deliveryType" value="home" title="4.99" checked = "checked" />&nbsp; | &nbsp;
    Collect from warehouse - no charge <input type="radio" name="deliveryType" value="trade" title="0" />
</p>
<section id="checkCost">
    <h2>Total cost</h2>
    Total <input type="text" name="total" id="total" size="10" readonly="readonly" />
</section>

JS:

var checkedRadioButtons = document.querySelectorAll('input[type="radio"]:checked');

您可以使用getAttribute函数

var checkedRadioButtons = document.querySelectorAll('input[type="radio"]:checked');
var total = 0;
for ( var i = 0 ;  i < checkedRadioButtons.length ; i++ ) {   
    total += Number( checkedRadioButtons[i].getAttribute('title') );
}
console.log( total );

使用getAttribute获取title属性值。

var checkedRadioButtons = document.querySelector('[name="deliveryType"]:checked');
document.getElementById("total").value = checkedRadioButtons.getAttribute("title");
<p>Home address - &pound;4.99
    <input type="radio" name="deliveryType" value="home" title="4.99" checked="checked" />&nbsp; | &nbsp; Collect from warehouse - no charge
    <input type="radio" name="deliveryType" value="trade" title="0" />
</p>
<section id="checkCost">
    
<h2>Total cost</h2>
Total
    <input type="text" name="total" id="total" size="10" readonly="readonly" />
</section>

演示:http://jsfiddle.net/kishoresahas/z75d0q3L

最新更新