“Botón de radio solo un JavaScript seleccionado” Código de respuesta

seleccionando solo un botón de radio

<!-- Just give all the radio buttons the same name. 
Html will then allow you to select only one. -->

<input type="radio" name="radAnswer" />
Ashamed Addax

Botón de radio solo un JavaScript seleccionado

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Radio Button</title>
</head>
<body>
    <p>Select your size:</p>
    <div>
        <input type="radio" name="size" value="XS" id="xs">
        <label for="xs">XS</label>
    </div>
    <div>
        <input type="radio" name="size" value="S" id="s">
        <label for="s">S</label>
    </div>
    <div>
        <input type="radio" name="size" value="M" id="m">
        <label for="m">M</label>
    </div>
    <div>
        <input type="radio" name="size" value="L" id="l">
        <label for="l">L</label>
    </div>
    <div>
        <input type="radio" name="size" value="XL" id="xl">
        <label for="xl">XL</label>
    </div>
    <div>
        <input type="radio" name="size" value="XXL" id="xxl">
        <label for="xxl">XXL</label>
    </div>
    <p>
        <button id="btn">Show Selected Value</button>
    </p>

    <p id="output"></p>

    <script>
        const btn = document.querySelector('#btn');        
        const radioButtons = document.querySelectorAll('input[name="size"]');
        btn.addEventListener("click", () => {
            let selectedSize;
            for (const radioButton of radioButtons) {
                if (radioButton.checked) {
                    selectedSize = radioButton.value;
                    break;
                }
            }
            // show the output:
            output.innerText = selectedSize ? `You selected ${selectedSize}` : `You haven't selected any size`;
        });
    </script>
</body>
</html>
Code language: HTML, XML (xml)
Ahmed Samir

Respuestas similares a “Botón de radio solo un JavaScript seleccionado”

Preguntas similares a “Botón de radio solo un JavaScript seleccionado”

Más respuestas relacionadas con “Botón de radio solo un JavaScript seleccionado” en JavaScript

Explore las respuestas de código populares por idioma

Explorar otros lenguajes de código