I would like to know what I can do so that the radio input works with its respective text input, since the 4 buttons interact with the same text input and it causes me conflict when making a larger form. I hope you can help me and thanks in advance.
//esperamos a que cargue el DOM
document.addEventListener('DOMContentLoaded', function() {
//seleccionamos los inputs tipo radio, recuerda que
//esto te trae un HTMLCollections, así que lo tienes que recorrer con un for
let inputs = document.querySelectorAll('input[type="radio"]');
//console.log(inputs[0]);
//cremos el for
for (let i = 0; i < inputs.length; i++)
//le agregamos a cada iteración un addEventListener de tipo change
//como su nombre lo indica al momento de cambiar de input tomará su valor
inputs[i].addEventListener('change', function() {
//Validamos que ese input tenga el atributo checked
if (this.checked) {
//si es así obtenemos su valor y lo agregamos al input.
document.getElementById("rInput").value = this.value;
}
})
})
<head>
<meta charset="utf-8">
<title>javascript - Obtain the value of a radio button</title>
</head>
<body>
<h1>Obtain the value of a radio button</h1>
<form id="form1">
<p>Deacuerdo: Si<input type="radio" name="deacuerdo" value="si"> No<input type="radio" name="deacuerdo" value="no"></p>
<div id="resultado"><input id="rInput" type="text"></div>
<p>Enterado: Si se<input type="radio" name="enterado" value="si se"> No se<input type="radio" name="enterado" value="no se"></p>
<div id="resultados"><input id="eInput" type="text"></div>
</form>
</body>
</html>
Friend, correcting your code, the only thing missing is to add the name in the if condition, to differentiate them from one another and thus, write their value in the corresponding textbox.
I add example
I leave you commented the part of the code that I added and I also made modifications to your HTML, what I did was save the first two radios and the
text
corresponding input in a div and in the other case the same, to know in which div the input is locatedtext
. I want to add the value of its radio, I hope it works for you, let her know if you have any questions.