TekMatix Help Blog

Search Help Categories

Use the search bar below to look for help articles you need.

Checkbox Order Form

How to Add Checkbox on the Order Form

June 01, 20233 min read

Use the snippet of code below to add a checkbox that users must select in order to finish a 1-Step or 2-Step-Order form. A link to your terms and conditions may also be included.

Please Note: If PayPal is the only Payment option connected to your account the script below will not work. We will work on finding another solution for those using PayPal only.

<script>
(function () {
  //****
  // If you want to update TOS with the content please add your correct location id
  // And create a blank form and get id then pass that form id on the formId varible
  //****

  const checkBoxLabel = "By checking this box, you agree to our ";
  const termsURL = "https://google.com";
  const termsText = "terms and conditions";

  const location_id = "4f6En2kmrDyqEdKKD68i00"; // Enter your valid location Id
  const formId = "ehVnSNE8GHO71wLkmt6r00"; // Enter a vaild form id
  const customFieldName = "accept_terms_and_conditions"; // Enter your custom field key

  class GOHLTECH_POST_FORM_DATA {
    constructor() {
      this.headers = {
        "Content-Type": "application/json",
      };
      this.baseURL = "https://msgsndr.com/";
    }

    async postFormData(formId, locationId, data, path) {
      const postBody = {
        ...data,
        formId: formId,
        location_id: locationId,
      };

      const requestOptions = {
        method: "POST",
        headers: this.headers,
        body: JSON.stringify(postBody),
        redirect: "follow",
      };

      try {
        const request = await fetch(this.baseURL + path, requestOptions);
        const response = await request.json();
        return response;
      } catch (err) {
        return err;
      }
    }
  }

  function createCheckBoxInnerHTML(checkBoxLabel, termsURL, termsText) {
    return ` ${checkBoxLabel} <a href='${termsURL}' target="_blank">${termsText}</a>`;
  }

  const store = {
    [customFieldName]: "",
  };

  const privacyStyles = `
    .custom_accept_container {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    margin-top: 15px;
    margin-bottom: 10px;
    }

    .custom_accept_container label {
    display: inline-flex;
    margin-left: 10px;
    }
  `;

  function appendStyle(stylesheet) {
    const style = document.createElement("style");
    style.innerHTML = stylesheet;
    const head = document.querySelector("head");
    head.append(style);
  }
  appendStyle(privacyStyles);

  const postForm = new GOHLTECH_POST_FORM_DATA();

  function getElementByFn(selector) {
    let elements = [];
    let intervalId;
    return new Promise((res, rej) => {
      intervalId = setInterval(() => {
        elements = document.querySelectorAll(selector);
        if (!elements.length) return;
        clearInterval(intervalId);
        if (elements.length === 1) return res(elements[0]);
        if (elements.length > 1) return res([...elements]);
      }, 300);

      setTimeout(() => {
        if (!elements.length) {
          clearInterval(intervalId);
          res(false);
          console.log(`${selector} elements not found`);
        }
      }, 2000);
    });
  }

  function enableSubmitButton(checkbox, button) {
    if (!button) return console.log("Please provide a button");
    if (!checkbox.checked) {
      button.style.pointerEvents = "none";
      button.style.opacity = 0.5;
      store.accept_terms_and_conditions = "";
    } else {
      button.style.pointerEvents = "auto";
      button.style.opacity = 1;
      store.accept_terms_and_conditions = "Yes";
    }
  }

  async function getStepButton() {
    const stepButton = await getElementByFn(
      ".c-order button.form-btn:not(.c-order .payment-content button.form-btn)",
    );
    if (!stepButton) return console.error("Form Button Not Found");
    stepButton.addEventListener("click", (e) => {
      appendTermsCheckBox();
    });
  }

  async function appendTermsCheckBox() {
    const formButtons = await getElementByFn(
      ".c-order .payment-content button.form-btn",
    );

    if (!formButtons.length) return console.log("Not Buttons Found!");

    formButtons.forEach((formButton, index) => {
      const checkBoxContainer = document.createElement("div");
      checkBoxContainer.classList = "custom_accept_container";
      const chekboxLabel = document.createElement("label");
      chekboxLabel.htmlFor = "accept_terms" + index;
      chekboxLabel.classList = "custom_accept";
      chekboxLabel.innerHTML = createCheckBoxInnerHTML(
        checkBoxLabel,
        termsURL,
        termsText,
      );
      const acceptCheck = document.createElement("input");
      acceptCheck.type = "checkbox";
      acceptCheck.id = "accept_terms" + index;
      checkBoxContainer.append(acceptCheck);
      checkBoxContainer.append(chekboxLabel);
      formButton.parentElement?.insertBefore(checkBoxContainer, formButton);

      if (checkBoxContainer.isConnected) {
        formButton.style.pointerEvents = "none";
        formButton.style.opacity = 0.5;
      }

      formButton.addEventListener("click", async (e) => {
        if (!formId || !location_id)
          return console.log("Location id and form id is required");
        await postForm.postFormData(formId, location_id, store, "form");
      });

      acceptCheck.addEventListener("change", () => {
        enableSubmitButton(acceptCheck, formButton);
      });
    });

    const stepBackButton = await getElementByFn(
      ".c-order .forward-shopping-details",
    );

    if (stepBackButton) {
      stepBackButton.addEventListener("click", getCheckoutType);
      stepBackButton.addEventListener("click", updateStore);
    }
  }

  async function getCheckoutType() {
    const orderForm = await getElementByFn(".c-order");
    if (!orderForm) return console.error("No order form found!");
    let isOneStepForm = orderForm.id.trim().includes("one-step-order");

    if (isOneStepForm) {
      appendTermsCheckBox();
    } else {
      getStepButton();
    }
  }

  async function updateStore() {
    const inputs = await getElementByFn(
      ".c-order .info input:not(input[type='checkbox'],input[type='radio'])",
    );

    if (!inputs.length) return console.log("No inputs found!");

    inputs.forEach((input) => {
      input.addEventListener("input", () => {
        store[input.name.trim()] = input.value;
      });
    });

    let intervalId;
    let isAllInputUpdated = 0;

    intervalId = setInterval(() => {
      inputs.forEach((input) => {
        if (!input.value) return;
        store[input.name.trim()] = input.value;
        isAllInputUpdated++;
        if (isAllInputUpdated === inputs.length) {
          clearInterval(intervalId);
          console.log("Updated");
        }
      });
    }, 200);

    setTimeout(() => {
      clearInterval(intervalId);
    }, 2000);
  }

  updateStore();
  getCheckoutType();
})();

</script>
Back to Blog

BECOME A TEKMATIX AFFILIATE

Copyright ©

2024 TekMatix. All rights reserved | support@tekmatix.com