tz-converter/templates/assets/js/index.js

81 lines
2.8 KiB
JavaScript

document.getElementById('time-converter-form').addEventListener('submit', function(event) {
event.preventDefault();
const fromTz = document.getElementById('from-tz').value;
const time = document.getElementById('time').value;
const toTzs = document.getElementById('to-tzs').value.split(',');
// Update URL with query parameters
const params = new URLSearchParams({
from_tz: fromTz,
time: time,
to_tzs: toTzs.join(',')
});
window.history.replaceState({}, '', `${window.location.pathname}?${params.toString()}`);
fetch('/api/v1/convert_multiple', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
from_tz: fromTz,
time: time,
to_tzs: toTzs
})
})
.then(response => response.json())
.then(data => {
const resultsDiv = document.getElementById('results');
resultsDiv.innerHTML = '<h2>Converted Times:</h2>';
const table = document.createElement('table');
table.classList.add('results-table');
const thead = document.createElement('thead');
const tbody = document.createElement('tbody');
const headerRow = document.createElement('tr');
const th1 = document.createElement('th');
th1.textContent = 'Timezone';
const th2 = document.createElement('th');
th2.textContent = 'Converted Time';
headerRow.appendChild(th1);
headerRow.appendChild(th2);
thead.appendChild(headerRow);
for (const [tz, convertedTime] of Object.entries(data)) {
const row = document.createElement('tr');
const cell1 = document.createElement('td');
cell1.textContent = tz;
const cell2 = document.createElement('td');
cell2.textContent = convertedTime;
row.appendChild(cell1);
row.appendChild(cell2);
tbody.appendChild(row);
}
table.appendChild(thead);
table.appendChild(tbody);
resultsDiv.appendChild(table);
})
.catch(error => {
console.error('Error:', error);
});
});
// Load parameters from URL if available
window.addEventListener('load', function() {
const params = new URLSearchParams(window.location.search);
const fromTz = params.get('from_tz');
const time = params.get('time');
const toTzs = params.get('to_tzs');
if (fromTz && time && toTzs) {
document.getElementById('from-tz').value = fromTz;
document.getElementById('time').value = time;
document.getElementById('to-tzs').value = toTzs;
// Trigger form submission to display results
document.getElementById('time-converter-form').dispatchEvent(new Event('submit'));
}
});