2
Answers

how to create multiple checkbox ?

Velladurai

Velladurai

Jun 19
456
1

how to create multiple checkbox if i checked checkbox i want to show the checked value then uncheck checkbox remove value

Answers (2)
5
Aman Gupta

Aman Gupta

37 35.2k 2.5m Jun 19

Hi Velladurai,

Please find the attached snippet for your issue.

Here is the dummy code that I'd developed for your usecase.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Checkbox Example</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 20px;
        }
        .checkbox-container {
            margin-bottom: 20px;
        }
        .selected-values {
            margin-top: 20px;
        }
    </style>
</head>
<body>

<div class="checkbox-container">
    <label><input type="checkbox" value="Option 1" class="checkbox"> Option 1</label>
    <label><input type="checkbox" value="Option 2" class="checkbox"> Option 2</label>
    <label><input type="checkbox" value="Option 3" class="checkbox"> Option 3</label>
    <label><input type="checkbox" value="Option 4" class="checkbox"> Option 4</label>
</div>

<div class="selected-values">
    <h3>Selected Values:</h3>
    <ul id="selectedValuesList">
        <!-- Selected values will appear here -->
    </ul>
</div>

<script src="script.js"></script>
</body>
</html>

 

document.addEventListener("DOMContentLoaded", () => {
    const checkboxes = document.querySelectorAll('.checkbox');
    const selectedValuesList = document.getElementById('selectedValuesList');

    checkboxes.forEach(checkbox => {
        checkbox.addEventListener('change', (event) => {
            const value = event.target.value;

            if (event.target.checked) {
                addValue(value);
            } else {
                removeValue(value);
            }
        });
    });

    function addValue(value) {
        const listItem = document.createElement('li');
        listItem.textContent = value;
        listItem.setAttribute('data-value', value);
        selectedValuesList.appendChild(listItem);
    }

    function removeValue(value) {
        const listItem = selectedValuesList.querySelector(`[data-value="${value}"]`);
        if (listItem) {
            selectedValuesList.removeChild(listItem);
        }
    }
});

Hope this will help you.

0
Sundaram Subramanian

Sundaram Subramanian

72 26.4k 1.4m Jun 19
Checkbox Example