5
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.
