简体   繁体   中英

How to add text into input area with javascript radio button

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> 
*/

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.

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/

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.

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