Javascript从输入标题的单选按钮获取金额

时间:2015-12-01 07:32:42

标签: javascript html

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

如何使用纯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');

2 个答案:

答案 0 :(得分:0)

你可以使用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 );

答案 1 :(得分:0)

使用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