Swee Hong Swee Hong - 3 months ago 16
HTML Question

Copy radio value using its ID to insert into input as value using JavaScript

I have some HTML code as follows:

<input name="bid" type="radio" value="1" id="1234"/>
<input name="bid" type="radio" value="2" id="5678"/>
<input type="text" id="paymount" name="paymount" value=""/>


Desired functionality:

When
radio=1
is checked, the
paymount
field value will show as
1234
. When
radio=2
is checked, the
paymount
field value will show as
5678
.

I have found posts on Stack Overflow, but a lot of them are related to hiding a text field.

Answer
<form name="radioForm">
    <input name="bid" type="radio" value="1" id="1234"/>
    <input name="bid" type="radio" value="2" id="5678"/>
    <input type="text" id="paymount" name="paymount" value=""/>
</form>     

<script type="text/javascript">
    var radio = document.radioForm.bid,
        input = document.getElementById('paymount');

    for(var i = 0; i < radio.length; i++) {
        radio[i].onclick = function() {            
            input.value = this.id;
        };
    }
</script>

jsFiddle

Comments