34198-vm/assets/js/main.js
2025-09-18 12:18:42 +00:00

76 lines
2.9 KiB
JavaScript

document.addEventListener('DOMContentLoaded', function () {
const beautyVotes = [];
const funnyVotes = [];
const beautyInput = document.getElementById('website_number_beauty');
const funnyInput = document.getElementById('website_number_funny');
const toastLiveExample = document.getElementById('liveToast');
const toast = new bootstrap.Toast(toastLiveExample);
document.querySelectorAll('.form-check-input[data-category]').forEach(checkbox => {
checkbox.addEventListener('change', function() {
const category = this.dataset.category;
const websiteNumber = this.dataset.websiteNumber;
const votes = (category === 'beauty') ? beautyVotes : funnyVotes;
const input = (category === 'beauty') ? beautyInput : funnyInput;
if (this.checked) {
if (votes.length >= 3) {
this.checked = false;
alert('You can only select up to 3 websites per category.');
return;
}
votes.push(websiteNumber);
} else {
const index = votes.indexOf(websiteNumber);
if (index > -1) {
votes.splice(index, 1);
}
}
votes.sort((a, b) => a - b);
input.value = votes.join(', ');
});
});
const handleFormSubmit = (form, event) => {
event.preventDefault();
const formData = new FormData(form);
const data = Object.fromEntries(formData.entries());
fetch('submit_vote.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(result => {
if (result.success) {
toast.show();
form.reset();
// Clear the votes and checkboxes for the submitted category
if (data.category === 'beauty') {
beautyVotes.length = 0;
document.querySelectorAll('input[data-category="beauty"]').forEach(cb => cb.checked = false);
beautyInput.value = '';
} else {
funnyVotes.length = 0;
document.querySelectorAll('input[data-category="funny"]').forEach(cb => cb.checked = false);
funnyInput.value = '';
}
} else {
alert('Error: ' + result.error);
}
})
.catch((error) => {
console.error('Error:', error);
alert('An error occurred while submitting your votes.');
});
};
document.getElementById('beautiful-form').addEventListener('submit', (event) => handleFormSubmit(event.target, event));
document.getElementById('funny-form').addEventListener('submit', (event) => handleFormSubmit(event.target, event));
});