Untitled

mail@pastecode.io avatar
unknown
javascript
a month ago
2.8 kB
7
Indexable
Never
document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady() {
  // Cordova is now initialized. Have fun!
  console.log("Running cordova-" + cordova.platformId + "@" + cordova.version);
}

let contacts = [];

function addContact() {
  const name = document.getElementById("name").value;
  const phone = document.getElementById("phone").value;

  // Regular expression to validate phone number (e.g., allows digits, spaces, dashes, and parentheses)
  const phoneRegex = /^[0-9\s\-()]+$/;

  if (name && phone) {
    if (
      phoneRegex.test(phone.trim()) &&
      (phone.length == 11 || phone.length == 8)
    ) {
      contacts.push({ name, phone });
      updateContactList();
      document.getElementById("name").value = "";
      document.getElementById("phone").value = "";
    } else {
      alert("Please enter a valid phone number.");
    }
  } else {
    alert("Please enter both name and phone number.");
  }
}

function updateContactList() {
  const contactList = document.getElementById("contactList");
  contactList.innerHTML = "";
  contacts.forEach((contact, index) => {
    const li = document.createElement("li");
    li.textContent = `${contact.name}: ${contact.phone}`;
    contactList.appendChild(li);
  });
}

function saveContacts() {
  const jsonString = JSON.stringify(contacts, null, 2);

  if (window.cordova && window.cordova.file) {
    // Save on Android platform using Cordova
    window.resolveLocalFileSystemURL(
      cordova.file.externalDataDirectory,
      function (dir) {
        dir.getFile(
          "contacts.json",
          { create: true },
          function (file) {
            file.createWriter(function (fileWriter) {
              fileWriter.onwriteend = function () {
                alert("File written successfully");
              };

              fileWriter.onerror = function (e) {
                console.error("Failed to write file: " + e.toString());
              };

              const blob = new Blob([jsonString], { type: "application/json" });
              fileWriter.write(blob);
            });
          },
          function (error) {
            console.error("Error getting file: " + error.toString());
          }
        );
      },
      function (error) {
        console.error("Error resolving file system URL: " + error.toString());
      }
    );
  } else {
    // Save on browser platform
    const blob = new Blob([jsonString], { type: "application/json" });
    const url = URL.createObjectURL(blob);

    const a = document.createElement("a");
    a.href = url;
    a.download = "contacts.json";
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  }
}
Leave a Comment