0

I am trying to achieve a function where-by a user would choose an option via a radio button and the value would be added into an input text box.

I used the onClick but wasn't efficient enough.

/*
button
<div onClick="    
document.forms['name_of_ the_form']['name_of_the_ input'].value += 'text you want to add to it'" > button </div> 
*/
1
  • 1
    show us the code you have. And do you want to use jQuery or just javascript? Commented Nov 12, 2015 at 4:14

3 Answers 3

1

This is what you can do:

var radioArray = document.getElementsByName("radio");
for (i = 0; i < radioArray.length; i++) {
    radioArray[i].onclick = alertText;
}

function alertText () {
    document.getElementById("text").innerHTML = this.value;
}

Live version: http://jsfiddle.net/mankinchi/sL4cfj7r/

"this" in the alertText function will refer to the actual element that has been clicked on.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use a bit of jQuery to achieve this quite easily.

HTML:

<input type="radio" name="radio" value="Something">Something
<input type="radio" name="radio" value="Something 2">Something 2
<input type="radio" name="radio" value="Something 3">Somethign 3
<textarea id="target"></textarea>

JS:

$(document).ready(function(){
    $('input[name=radio]:radio').on('change', function() {
        $('#target').val( $(this).val() );
    });
});

http://jsfiddle.net/1an0p4z6/

----- Non jQuery -----

HTML:

<input type="radio" name="radio" class="radio" value="Something">Something
<input type="radio" name="radio" class="radio" value="Something 2">Something 2
<input type="radio" name="radio" class="radio" value="Something 3">Somethign 3

<textarea id="target"></textarea>

JS:

var buttons = document.querySelectorAll('.radio');

for( i=0; i<buttons.length; i++ ) {
    buttons[i].addEventListener('change',function(){
        document.querySelector('#target').value = this.value;
    });
}

http://jsfiddle.net/jh10nf5e/1/

3 Comments

Actually i want to use javascript not JQuery
@MrJay check mine for javascript version
Where would i put the value of the radio input in the javascript code
0

Using javascript I can give you an example:

function myfunction() {
    var radios = document.getElementsByName('radname');
    if (radios[0].checked) {
        radvalue = radios[0].value
    } else if (radios[1].checked) {
        radvalue = radios[1].value
    }
    document.getElementById('txt').value = radvalue;
}

DEMO

Use this just as an reference, will help you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.