-1

I am trying to copy the value from the selected radio button to display in a text box. However, I can not get this to work. I have copied my code below.

Is anyone able to help me please?

function sync()
{
  var n4 = document.getElementById('n4').checked;
  var n1 = document.getElementById('n1');
  n1.value = n4.value;
}
<form action="" id="n4"  onkeyup="sync()">
  <input type="radio" name="gender" value="male" id"4" onkeyup="sync()"> Male<br>
  <input type="radio" name="gender" value="female" onkeyup="sync()"> Female<br>
  <input type="radio" name="gender" value="other" onkeyup="sync()"> Other
</form>

<input type="text" name="n1" id="n1" >
Durga
  • 15,263
  • 2
  • 28
  • 52

3 Answers3

2

function sync(el)
{
  var n1 = document.getElementById('n1');
  n1.value = el.value;
}
<form action="" id="n4">
  <input type="radio" name="gender" value="male" id"4" onchange="sync(this)"> Male<br>
  <input type="radio" name="gender" value="female" onchange="sync(this)"> Female<br>
  <input type="radio" name="gender" value="other" onchange="sync(this)"> Other
</form>

<input type="text" name="n1" id="n1" >

Use onchange and pass the element and get value from it.

Durga
  • 15,263
  • 2
  • 28
  • 52
1

I have changed a bit of code. First of all i used the onchange event. After that ive created an array of radio buttons with the same class name. Everytime a radio button changes it will loop and return the checked value in the input field.

function sync() {
  var radios = document.getElementsByName('gender');
  for(var i = 0; i < radios.length; i++){
    if(radios[i].checked){
      n1.value = radios[i].value;
    };
  };
};
<form action="" id="n4"  onkeyup="sync()">
<input type="radio" name="gender" value="male" id"4" onchange="sync()"> Male<br>
<input type="radio" name="gender" value="female" onchange="sync()"> Female<br>
<input type="radio" name="gender" value="other" onchange="sync()"> Other
</form>


<input type="text" name="n1" id="n1" >
Rick Bronger
  • 330
  • 1
  • 15
-1

Please use the below to set the value. As per your code you are just assigning values to each other.

function sync()
{
var n4 = document.getElementById('n4').checked;
    document.getElementById("n1").value = n4;
}
user8271644
  • 219
  • 2
  • 8
  • The OP is setting the value of the textbox to the `value` property of a Boolean, which is undefined. Your code will only set the textbox's value to `true` or `false` depending on whether the first radio button is checked or not, which does not appear to be what the OP wants. – Heretic Monkey Jul 28 '17 at 14:13