Need help with java code

Lakshmi Polisetti 20 Reputation points
2026-01-12T18:03:05.7633333+00:00
// MOLF - Fill ONLY (1 AR at a time). No Submit clicks.
// Paste 1 Excel row (TAB-separated, NO header):
// FirstName | MiddleName | LastName | Role | JobTitle | Email | PhoneType | PhoneNumber | Country
(function () {
  // Expose globally so bookmarklet can call
  window.molfFillOneFromPrompt = function () {
    // ESC stop (optional)
    window._molfStop = false;
    window.addEventListener('keydown', function (e) {
      if (e.key === 'Escape') {
        window._molfStop = true;
        console.warn('[MOLF] ESC pressed. Stopping.');
      }
    }, { once: true });
    const last = window._molfLastOneRow || "";
    let rawRow = "";
    // ALWAYS ask if last data exists
    if (last) {
      const useLast = window.confirm(
        "MOLF:\nUse the same AR data as last time?\n\nOK = reuse\nCancel = paste new"
      );
      if (useLast) {
        rawRow = last;
      }
    }
    // If no reuse, prompt for new
    if (!rawRow) {
      rawRow = window.prompt(
        "MOLF: Paste ONE Excel row (NO header).\n" +
        "Columns (TAB-separated):\n" +
        "FirstName | MiddleName | LastName | Role | JobTitle | Email | PhoneType | PhoneNumber | Country",
        ""
      ) || "";
      rawRow = rawRow.trim();
      if (!rawRow) {
        console.warn("[MOLF] No row pasted. Aborting.");
        return;
      }
      window._molfLastOneRow = rawRow; // remember for next time
    }
    // Parse: real TAB or literal \t
    const cells = rawRow.split(/\t|\\t/g).map(c => (c ?? "").trim());
    if (cells.length < 9) {
      console.warn(`[MOLF] Row has fewer than 9 columns (got ${cells.length}).`, cells);
      return;
    }
    const [
      firstName,
      middleName,
      lastName,
      role,
      jobTitle,
      email,
      phoneType,
      phoneNumber,
      country
    ] = cells;
    const ar = { firstName, middleName, lastName, role, jobTitle, email, phoneType, phoneNumber, country };
    console.log("[MOLF] Filling 1 AR:", ar);
    function normalize(str) {
      return String(str || "")
        .toLowerCase()
        .replace(/\s+/g, "")
        .replace(/-/g, "");
    }
    function setInputValue(el, value, label) {
      if (!el) {
        console.warn(`[MOLF] Field not found: ${label}`);
        return;
      }
      if (window._molfStop) return;
      el.focus();
      el.value = value ?? "";
      el.dispatchEvent(new Event("input", { bubbles: true }));
      el.dispatchEvent(new Event("change", { bubbles: true }));
      el.blur();
      console.log(`[MOLF] ${label} filled`);
    }
    function setSelectByTextLoose(el, text, label) {
      if (!el) {
        console.warn(`[MOLF] Select not found: ${label}`);
        return;
      }
      if (!text) {
        console.warn(`[MOLF] ${label}: empty value, leaving as is`);
        return;
      }
      if (window._molfStop) return;
      const target = normalize(text);
      let found = false;
      for (const opt of el.options) {
        if (normalize(opt.text) === target) {
          el.value = opt.value;
          el.dispatchEvent(new Event("change", { bubbles: true }));
          el.dispatchEvent(new Event("input", { bubbles: true }));
          console.log(`[MOLF] ${label} selected: ${opt.text}`);
          found = true;
          break;
        }
      }
      if (!found) console.warn(`[MOLF] ${label}: option not found for "${text}"`);
    }
    // ---- Map fields ----
    const firstNameEl  = document.getElementById("FirstName");
    const middleNameEl = document.getElementById("MiddleName");
    const lastNameEl   = document.getElementById("LastName");
    const roleSel      = document.getElementById("RoleType");
    const jobTitleEl   = document.getElementById("JobTitle");
    const emailEl      = document.getElementById("EmailAddress");
    const phoneTypeSel = document.getElementById("PhoneNumberType");
    const phoneEl      = document.getElementById("PhoneNumber") || document.querySelector('input[name="PhoneNumber"]');
    const countrySel   = document.getElementById("Country") || document.querySelector('select[name="Country"]');
    // ---- Fill (Middle Name optional) ----
    setInputValue(firstNameEl,  firstName,  "First Name");
    setInputValue(middleNameEl, middleName, "Middle Name");
    setInputValue(lastNameEl,   lastName,   "Last Name");
    setSelectByTextLoose(roleSel, role, "Role");
    setInputValue(jobTitleEl, jobTitle, "Job Title");
    setInputValue(emailEl, email, "Email");
    setSelectByTextLoose(phoneTypeSel, phoneType, "Phone Type");
    const cleanPhone = String(phoneNumber || "").replace(/\s+/g, " ").trim();
    setInputValue(phoneEl, cleanPhone, "Phone Number");
    setSelectByTextLoose(countrySel, country, "Country");
    console.log("[MOLF] Fill-only done. Review and SUBMIT manually.");
  };
  // Auto-run once when you run the snippet
  window.molfFillOneFromPrompt();
})();
Microsoft 365 and Office | Development | Office JavaScript API
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Flora-T 9,205 Reputation points Microsoft External Staff Moderator
    2026-01-13T13:52:41.6433333+00:00

    Hi Lakshmi Polisetti

    Thank you for reaching out to Microsoft Q&A Forum and sharing your experience.

    This JavaScript appears to be a helper script/bookmarklet for automating the filling of a web form using data pasted from an Excel row.

    However, you haven't specified exactly what isn't working. Please update your question with the following details:

    • How are you running this? Is this a browser Bookmarklet, a snippet you are pasting into the Console, or running via an extension?
    • What happens when you run it? Does nothing happen, or does it only fill some fields?
    • Are there errors? Please press F12 to open the Developer Tools, select the Console tab, run the script, and check if any red text or specific error messages appear.

    Because this is a public forum, so I suggest that you will send these details to the Private Messages in this thread to protect your personal data. Your cooperation will help me provide the most accurate and effective solution.

    User's image

    In the meantime, the most common reasons this specific script would fail are:

    • Mismatched IDs: This script looks for exact HTML IDs (like document.getElementById("FirstName")). If the website you are using has different IDs (like id="input-first-name" or id="ember321"), the script will not find the fields.
    • Timing Issues: If you run the script before the page has completely finished loading, the elements won't exist yet.

    Please let me know how you get on, as your feedback is valuable to the community.


    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.