user2988501
user2988501

Reputation: 107

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 ; 
  }
}

}

Upvotes: 0

Views: 278

Answers (1)

Suman Bogati
Suman Bogati

Reputation: 6349

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

Upvotes: 2

Related Questions