“Przycisk opcji tylko jeden wybrany JavaScript” Kod odpowiedzi

Wybór tylko jednego przycisku opcji

<!-- 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

Przycisk opcji tylko jeden wybrany JavaScript

<!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

Odpowiedzi podobne do “Przycisk opcji tylko jeden wybrany JavaScript”

Pytania podobne do “Przycisk opcji tylko jeden wybrany JavaScript”

Więcej pokrewnych odpowiedzi na “Przycisk opcji tylko jeden wybrany JavaScript” w JavaScript

Przeglądaj popularne odpowiedzi na kod według języka

Przeglądaj inne języki kodu