Tengo un contenedor con 3 botones de radio y 2 de los botones de radio tienen otros botones de radio junto a ellos, pero sus pantallas no son ninguna. Cuando hago clic en el botón de radio, quiero mostrar los botones de radio ocultos y cuando hago clic en otro botón de radio, quiero que no se muestre ninguno nuevamente.
`function showHiddenText() { if (document.getElementById("diger").checked) { const hiddenInput = document.getElementById("hidden-input"); hiddenInput.style.display = "block"; } else if (document.getElementById("diger").checked == false) { hiddenInput.style.display = "none"; } }`Es una función simple que escribo para hacer eso, pero si parte no funciona. Cuando muestro botones de radio ocultos, no desaparecen nunca más. parte oculta de los botones de radio
Las variables const tienen un alcance de bloque. Entonces, en la declaración else if , hiddenInput no está definido.
Muévalo encima de las declaraciones
function showHiddenText() { const hiddenInput = document.getElementById("hidden-input"); if (document.getElementById("diger").checked) { hiddenInput.style.display = "block"; } else if (document.getElementById("diger").checked == false) { hiddenInput.style.display = "none"; } } Por cierto, puede hacerlo más simple reemplazando la instrucción else if con else :
function showHiddenText() { const hiddenInput = document.getElementById("hidden-input"); if (document.getElementById("diger").checked) { hiddenInput.style.display = "block"; } else { hiddenInput.style.display = "none"; } }O incluso más:
function showHiddenText() { const hiddenInput = document.getElementById("hidden-input"); if (document.getElementById("diger").checked) { hiddenInput.style.display = "block"; return true; // you can return anything here } hiddenInput.style.display = "none"; return false; // and here (it is not necessary to return here) }Asegúrese de que sus botones de opción tengan el mismo nombre. Los botones de opción con el mismo nombre se comparan entre sí. Agregue onclick="showHiddenText()" a las entradas, luego:
html:
<input type="radio" name="btn" id="diger" onclick="showHiddenText()"> <input type="radio" name="btn" onclick="showHiddenText()"> <input type="radio" id="hidden-input">js:
function showHiddenText() { if (document.getElementById("diger").checked) { document.getElementById("hidden-input").style.display = 'block' } else{ document.getElementById("hidden-input").style.display = 'none' } }