简体   繁体   中英

Radio values in text box on page load

I'm wondering if anyone can help me, I'm trying to load the checked radio button value to the text box when the page is loaded? Here's my 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>

And her is the 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 ; 
  }
}

}

Make this two lines available when body is being loaded, You are putting the value by script only when the radio button is clicked.

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

Something like this.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM