Menu Close

How to append the Checkbox Value to another input Using JavaScript?

Codeamend

Here we are using the JavaScript click() function to assign the value to the textbox with the action of checkbox. Whenever the checkbox is clicked to check or uncheck, it assigns the respective return value into the textbox.

<!DOCTYPE html>
<html>
<body>

<p>Gender:</p>

<label for="myCheck">Male:</label> 
<input type="checkbox" id="check1" name="check" value="Male" onclick="myFunction()">

<br>
<br>
<label for="myCheck">Female:</label> 
<input type="checkbox" id="check2" name="check" value="Female" onclick="myFunction1()">

<br>
<br>
<input type="text" id="myText" value="Not Selected">

<script>
function myFunction() {

  var checkBox = document.getElementById("check1");
  var text = document.getElementById("check1").value;
  var checkBox1 = document.getElementById("check2");

  if (checkBox.checked == true){
  	document.getElementById("myText").value = text;
  	checkBox1.checked = false;
  } else {
  	document.getElementById("myText").value = "Not Selected";
  	checkBox.checked = false;
  	checkBox1.checked = false;
  }
}

function myFunction1() {

  var checkBox = document.getElementById("check1");
  var checkBox1 = document.getElementById("check2");
  var text1 = document.getElementById("check2").value;

  if (checkBox1.checked == true){
  	document.getElementById("myText").value = text1;
  	checkBox.checked = false;
  } else {
  	document.getElementById("myText").value = "Not Selected";
  	checkBox.checked = false;
  	checkBox1.checked = false;
  }
}
</script>

</body>
</html> 
Posted in HTML, JavaScript

You can also read...