Nithi
Nithi

Reputation: 166

populate text box on click of radio button

I have 3 radio buttons, when one of them is selected I want to automatically put text in a textbox. For example, If the user selected the 'Yes' radio button, I want the text 'Yes' put in the textbox, and if they select another radio button I want it to be cleared.

Can anyone help me??

Upvotes: 1

Views: 11326

Answers (4)

goncaloGomes
goncaloGomes

Reputation: 163

Try this. Should be cross-browser, but it's worth testing in a few older browsers.

<html>
<body>
<p><span>User clicked: </span><input type="text" id="userAnswer"/></p>
<input type="radio" name="userAnswerChoice" value="Yes"/>
<input type="radio" name="userAnswerChoice" value="No"/>
<input type="radio" name="userAnswerChoice" value="Maybe"/>
<script type="text/javascript">
function handleUserAnswer(e){
    var el = e.target || e.srcElement;
    document.getElementById('userAnswer').value = el.value;
}
var radios = document.getElementsByTagName('input');
for(var i = 0; i<radios.length; i++){
    var r = radios[i];
    if(r.getAttribute('name') == 'userAnswerChoice'){
        if(r.addEventListener){
            r.addEventListener('change',handleUserAnswer);
        }else if(r.attachEvent){
            r.attachEvent('onchange',handleUserAnswer);
        }else{
            r.onChange = handleUserAnswer;
        }
    }
}
</script>
</body>
</html>

Upvotes: 3

Viral Shah
Viral Shah

Reputation: 2246

do you want this?

http://jsfiddle.net/viralshah/KNct8/3/

Hope this resolve your problem.

Upvotes: 4

polin
polin

Reputation: 2835

This might help you

<form action="test1.asp" id="testform">
<input type="text" id="test3" value="">
<input type="radio" id="submit" onclick="modify_value()"/>
</form>
<script type="text/javascript">
function modify_value()
{
var hidden_field = document.getElementById('test3');
hidden_field.value = 'testvalue';

}
</script>

Upvotes: 1

gabrjan
gabrjan

Reputation: 3049

U have an onclick event so add onclick="function" and in that function u set text... U can get text from radio box with some javascript like that How do I get the text of a radio button (not the value)

Upvotes: 0

Related Questions