Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show radio button value in an input

I have radio buttons with the same name and same id, Which are dynamic data, I want to show these radio buttons values in input but when I am checking radio button only first radio button value is showing in input even if I check on second radio or third radio button.

I have three input type radio with the same name and same id but with different values, I am checking second and third radio button but it is showing only first radio button value in input.

<!DOCTYPE html>
<html>
<body>

<input type="radio" name="colors" onclick="myFunction()" value="red" id="myRadio">Red color
<input type="radio" name="colors" onclick="myFunction()" value="blue" id="myRadio">Blue color
<input type="radio" name="colors" onclick="myFunction()" value="green" id="myRadio">Green color


<input type="text" id="demo">

<script>
function myFunction() {
  var x = document.getElementById("myRadio").value;
  document.getElementById("demo").value = x;
}
</script>

</body>
</html>

When I check on red color then its value should show on input type with id demo and if I check green or blue then it should show these value in input with id demo.

like image 703
rahul Avatar asked Jan 04 '19 12:01

rahul


2 Answers

You cant have more than one element with the same ID since IDs should be unique. You should replace them with a class and then target the class name instead.

Also, avoid writing your JavaScript inline and use event listeners instead like this:

/* JavaScript */

var radio = document.querySelectorAll(".myRadio");
var demo = document.getElementById("demo");
  
function checkBox(e){
	demo.value = e.target.value;
}

radio.forEach(check => {
	check.addEventListener("click", checkBox);
});
<!-- HTML -->

<input type="radio" name="colors" value="red" class="myRadio">Red color
<input type="radio" name="colors" value="blue" class="myRadio">Blue color
<input type="radio" name="colors" value="green" class="myRadio">Green color


<input type="text" id="demo">
like image 169
AndrewL64 Avatar answered Sep 20 '22 16:09

AndrewL64


You can pass the event to the myFunction function and use that to determine which radio button was clicked, here is an example:

function myFunction(event) {
  document.getElementById("demo").value = event.target.value;
}
<!DOCTYPE html>
<html>
<body>

<input type="radio" name="colors" onclick="myFunction(event)" value="red" id="myRadio">Red color
<input type="radio" name="colors" onclick="myFunction(event)" value="blue" id="myRadio">Blue color
<input type="radio" name="colors" onclick="myFunction(event)" value="green" id="myRadio">Green color


<input type="text" id="demo">

</body>
</html>
like image 31
Titus Avatar answered Sep 19 '22 16:09

Titus