页面加载时文本框中的无线电值

时间:2014-02-26 14:17:13

标签: javascript html textbox radio-button

我想知道是否有人可以帮助我,我正在尝试在页面加载时将选中的单选按钮值加载到文本框中? 这是我的HTML

<h2>Configuration</h2>
<div>
<input type ="radio" id="gtmanual" name="car" value="277790.00" checked="checked" >
<label for ="gtmanual">GT Manual -  &euro; 27,7790.00 </label>
<br>
<input type ="radio" id="gtauto" name="car" value="28,500.00" >
<label for ="gtauto">GT Automatic -  &euro; 28,500.00 </label>
<br>
<input type ="radio" id="gtsmanual" name="car" value="32,450.00">
<label for ="gtsmanual">GT-S Manual -  &euro; 32,450.00 </label>
<br>
<input type ="radio" id="gtmanual" name="car" value="33,155.00">
<label for ="gtsauto">GT-S Auto -  &euro; 33,155.00 </label>
 <br>
<div class="col-sm-4">
<input type="text" id="total" readonly>
</div>
</div>

她就是javascript

window.addEventListener("load", getvalue, false);
function getvalue()
{

var rad = document.getElementsByName('car');
var value = null;
for(var i = 0; i < rad.length; i++) {
    rad[i].onclick = function() {
    value=document.querySelector('input[name="car"]:checked').value;
    document.getElementById('total').value=value ; 
  }
}

}

1 个答案:

答案 0 :(得分:2)

在加载正文时使这两行可用。只有在单击单选按钮时才按脚本放置值。

var value=document.querySelector('input[name="car"]:checked').value;
document.getElementById('total').value=value ; 

像这样。

window.addEventListener("load", getvalue, false);

//this would run when body is loaded
var value=document.querySelector('input[name="car"]:checked').value;
document.getElementById('total').value=value ; 

function getvalue(){
    var rad = document.getElementsByName('car');
    for(var i = 0; i < rad.length; i++) {
        rad[i].onclick = function() {
            //this would run only when radio button is clicked
            value=document.querySelector('input[name="car"]:checked').value;
            document.getElementById('total').value=value ; 
        }
    }
}

DEMO