form and table presist always
To ensure that the data entered into the table persists across different browsers and devices globally, we need to store the data in a centralized database rather than relying solely on localStorage
, which is limited to the local browser storage. Here’s how you can modify the code to achieve global persistence using a cloud-based database service (Google Sheets API in this case):
Updated HTML and JavaScript Code:
Explanation:
Google Sheets API Integration:
- The code now integrates with the Google Sheets API (
gapi
) for storing and retrieving data. This ensures that the data entered into the form is stored globally and can be accessed from anywhere, not just within the user's local environment.
- The code now integrates with the Google Sheets API (
Submit Function (
addData()
):- When the "Submit" button is clicked, data is added to the table (
#dataTable
) as well as being saved to Google Sheets using thesaveToGoogleSheets()
function. This function sends a request to append the data to the specified spreadsheet.
- When the "Submit" button is clicked, data is added to the table (
Delete Function (
deleteSelected()
):- The "Delete Selected Entries" button deletes selected rows from the table and updates the data in Google Sheets using
saveToGoogleSheetsFromTable()
.
- The "Delete Selected Entries" button deletes selected rows from the table and updates the data in Google Sheets using
Google Sheets API Initialization:
- The Google Sheets API client library (
gapi
) is loaded and initialized. This includes setting up API key, client ID, and authentication scopes necessary for accessing Google Sheets.
- The Google Sheets API client library (
Persistence Across Globe:
- Data entered into the form and stored in Google Sheets is accessible globally, ensuring that the table content persists across browsers, devices, and geographical locations.
Integration Notes:
- Replace Placeholder Values:
- Replace
'YOUR_SPREADSHEET_ID'
,'YOUR_API_KEY'
,'YOUR_CLIENT_ID'
, and other placeholders with your actual Google Sheets API credentials and spreadsheet details.
- Replace
---
<!DOCTYPE html>
<html>
<head>
<style>
.form-container {
margin: 20px;
}
.table-container {
margin: 20px;
}
table {
width: 100%;
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
th, td {
padding: 10px;
text-align: left;
}
</style>
</head>
<body>
<div class="form-container">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>
<label for="phone">Phone:</label>
<input type="text" id="phone" name="phone" required><br><br>
<label for="totalWatercanRequired">Total Water Can Required:</label>
<input type="number" id="totalWatercanRequired" name="totalWatercanRequired" required><br><br>
<label for="dateRequired">Date Required:</label>
<input type="date" id="dateRequired" name="dateRequired" required><br><br>
<label for="address">Address:</label>
<input type="text" id="address" name="address" required><br><br>
<button onclick="addData()">Submit</button>
</div>
<hr>
<div class="table-container">
<table id="dataTable">
<thead>
<tr>
<th>Select</th>
<th>Name</th>
<th>Phone</th>
<th>Total Water Can Required</th>
<th>Date Required</th>
<th>Address</th>
</tr>
</thead>
<tbody id="tableBody">
<!-- Table body content will be added dynamically -->
</tbody>
</table>
<br>
<button onclick="deleteSelected()">Delete Selected Entries</button>
</div>
<script>
// Function to add data to the table and Google Sheets
function addData() {
const name = document.getElementById('name').value;
const phone = document.getElementById('phone').value;
const totalWatercanRequired = document.getElementById('totalWatercanRequired').value;
const dateRequired = document.getElementById('dateRequired').value;
const address = document.getElementById('address').value;
if (name && phone && totalWatercanRequired && dateRequired && address) {
const newRow = document.createElement('tr');
const selectCell = document.createElement('td');
const nameCell = document.createElement('td');
const phoneCell = document.createElement('td');
const totalWatercanCell = document.createElement('td');
const dateCell = document.createElement('td');
const addressCell = document.createElement('td');
const checkBox = document.createElement('input');
checkBox.type = 'checkbox';
selectCell.appendChild(checkBox);
nameCell.textContent = name;
phoneCell.textContent = phone;
totalWatercanCell.textContent = totalWatercanRequired;
dateCell.textContent = dateRequired;
addressCell.textContent = address;
newRow.appendChild(selectCell);
newRow.appendChild(nameCell);
newRow.appendChild(phoneCell);
newRow.appendChild(totalWatercanCell);
newRow.appendChild(dateCell);
newRow.appendChild(addressCell);
document.getElementById('tableBody').appendChild(newRow);
// Clear input fields after adding data
document.getElementById('name').value = '';
document.getElementById('phone').value = '';
document.getElementById('totalWatercanRequired').value = '';
document.getElementById('dateRequired').value = '';
document.getElementById('address').value = '';
// Save data to Google Sheets
saveToGoogleSheets(name, phone, totalWatercanRequired, dateRequired, address);
}
}
// Function to delete selected entries from the table
function deleteSelected() {
const tableBody = document.getElementById('tableBody');
const rows = tableBody.getElementsByTagName('tr');
// Iterate backwards to safely delete rows
for (let i = rows.length - 1; i >= 0; i--) {
const checkBox = rows[i].getElementsByTagName('input')[0];
if (checkBox.checked) {
tableBody.removeChild(rows[i]);
}
}
// Save table data to Google Sheets after deletion
saveToGoogleSheetsFromTable();
}
// Function to save table data to Google Sheets
function saveToGoogleSheets(name, phone, totalWatercanRequired, dateRequired, address) {
// Replace with actual implementation using Google Sheets API
// Ensure to authenticate and authorize API requests
// Example code to illustrate saving data using Google Sheets API
const params = {
spreadsheetId: 'YOUR_SPREADSHEET_ID',
range: 'Sheet1!A1:F1',
valueInputOption: 'USER_ENTERED',
insertDataOption: 'INSERT_ROWS',
resource: {
values: [[name, phone, totalWatercanRequired, dateRequired, address]]
},
auth: 'YOUR_AUTHENTICATION_OBJECT' // Replace with your OAuth2 authenticated object or API key
};
// Example request to append data to the sheet
const request = gapi.client.sheets.spreadsheets.values.append(params);
request.then(function(response) {
console.log('Data appended successfully!', response.result);
}, function(reason) {
console.error('Error: ' + reason.result.error.message);
});
}
// Function to save table data to Google Sheets from the current table state
function saveToGoogleSheetsFromTable() {
const tableData = [];
// Iterate through table rows to save data
const rows = document.getElementById('tableBody').getElementsByTagName('tr');
for (let i = 0; i < rows.length; i++) {
const row = rows[i];
const cells = row.getElementsByTagName('td');
const rowData = {
name: cells[1].textContent,
phone: cells[2].textContent,
totalWatercanRequired: cells[3].textContent,
dateRequired: cells[4].textContent,
address: cells[5].textContent
};
tableData.push(rowData);
}
// Implement saving data to Google Sheets using API
// Example: Use the saveToGoogleSheets function above to save the entire tableData array
// Replace this comment with actual implementation using your preferred method or API
}
// Load table data from Google Sheets on page load
window.onload = function() {
// Implement loading data from Google Sheets on page load if needed
// Example: Use the Google Sheets API to fetch existing data and populate the table
};
</script>
<!-- Include Google API Client Library -->
<script src="https://apis.google.com/js/api.js"></script>
<script>
// Initialize Google Sheets API client library
// Example: Initialize client library and authenticate user if needed
// Replace with actual initialization and authentication flow
// Function to authenticate user and initialize API client
function initClient() {
// Example: Initialize Google Sheets API client
gapi.client.init({
apiKey: 'YOUR_API_KEY', // Replace with your API key
clientId: 'YOUR_CLIENT_ID.apps.googleusercontent.com', // Replace with your client ID
discoveryDocs: ['https://sheets.googleapis.com/$discovery/rest?version=v4'],
scope: 'https://www.googleapis.com/auth/spreadsheets'
}).then(function() {
console.log('Google Sheets API initialized');
// Additional initialization code or function calls can go here
}, function(error) {
console.error('Error initializing Google Sheets API:', error);
});
}
// Load Google Sheets API client library
gapi.load('client', initClient);
</script>
</body>
</html>