Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk4 min

Autofill Related Inputs When a User Types a Competition Name with JavaScript

Build a button-free JavaScript form that looks up a competition name and fills four related inputs as the value changes.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Listen for the main field’s input event, use its value as a key in a competition data map, and copy the matching record into comptype, compclass, comp_badge, and colours. This works while the user types and also handles a selection from a connected <datalist> without a separate button.

Use one record per competition

Rather than writing a separate event handler for every competition, keep the related values together in an object. The competition name is the lookup key; each matching record supplies the four fields to fill.

<label for="competition-name">Competition</label>
<input id="competition-name" name="competition" list="competition" autocomplete="off">
<datalist id="competition">
  <option value="La Liga"></option>
  <option value="UEFA Champions League"></option>
</datalist>

<label for="comptype">Type</label>
<input id="comptype" name="comptype">
<label for="compclass">Class</label>
<input id="compclass" name="compclass">
<label for="comp-badge">Badge</label>
<input id="comp-badge" name="comp_badge">
<label for="colours">Colours</label>
<input id="colours" name="colours">

<script src="app.js" defer></script>

The option values and the object keys must match after normalization. Add the rest of your competitions to the same map.

React to typing and datalist selection

The input event is the appropriate single listener for this form: it fires as the value changes, including edits made by the user and a value chosen from the datalist in this example. The archived SitePoint discussion used keyup for typed text and later demonstrated input for its datalist example; its 2017 observations do not establish current browser compatibility or form-submission behavior.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const competitions = {
  "la liga": {
    comptype: "League",
    compclass: "Domestic",
    comp_badge: "la-liga.png",
    colours: "red, yellow"
  },
  "uefa champions league": {
    comptype: "Cup",
    compclass: "European",
    comp_badge: "champions-league.png",
    colours: "blue, white"
  }
};

const nameInput = document.querySelector("#competition-name");
const fields = {
  comptype: document.querySelector("#comptype"),
  compclass: document.querySelector("#compclass"),
  comp_badge: document.querySelector("#comp-badge"),
  colours: document.querySelector("#colours")
};

function normalize(value) {
  return value.trim().toLocaleLowerCase();
}

nameInput.addEventListener("input", () => {
  const competition = competitions[normalize(nameInput.value)];

  if (!competition) {
    Object.values(fields).forEach((field) => {
      field.value = "";
    });
    return;
  }

  Object.entries(fields).forEach(([key, field]) => {
    field.value = competition[key] ?? "";
  });
});

trim() ignores accidental spaces, while lowercasing makes the lookup case-insensitive. If names must be case-sensitive, remove the lowercasing from both the keys and normalize().

What happens when there is no match?

Clear stale values

The example clears all dependent fields whenever the name is incomplete or unknown. This prevents details for the previously selected competition from remaining visible beside a different name.

Show an explicit status

For a form that needs feedback, add a status element and update it only when the lookup fails.

<p id="competition-status" role="status" aria-live="polite"></p>

<script>
const status = document.querySelector("#competition-status");

nameInput.addEventListener("input", () => {
  const competition = competitions[normalize(nameInput.value)];

  if (!competition) {
    Object.values(fields).forEach((field) => field.value = "");
    status.textContent = nameInput.value.trim()
      ? "No competition found."
      : "";
    return;
  }

  Object.entries(fields).forEach(([key, field]) => {
    field.value = competition[key] ?? "";
  });
  status.textContent = "Competition details filled.";
});
</script>

Why not use only keyup?

keyup responds to released keyboard keys, so it is narrower than a value-change listener. It does not represent every way an input can change, such as selecting a datalist option, pasting, or other non-keyboard edits. The SitePoint reply’s keyup example is useful for its original typed-input case, but input avoids maintaining separate handlers for those cases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A change listener is different: it is intended for a committed change rather than each edit. Use it when dependent fields should update after the control is committed, not while the user is still typing. The related 2017 example suggested combining keyup and change for a datetime-local field; that historical example is not a rule for every input type.

Scaling the map to 15 competitions

Add records without changing the event handler:

competitions["premier league"] = {
  comptype: "League",
  compclass: "Domestic",
  comp_badge: "premier-league.png",
  colours: "purple, white"
};

For larger datasets, keep the records in JSON and load them before attaching the listener. Validate any server-submitted value independently; client-side autofill improves the interface but is not a security boundary.

Common failure points

  • Script runs too early: use defer as shown, place the script after the form, or wait for DOM readiness.
  • Selector mismatch: verify that every JavaScript selector matches the actual element’s id.
  • Key mismatch: normalize the input and map keys consistently; punctuation and spelling still matter.
  • Unexpected blank values: ensure each record contains the same property names used in fields.
  • Stale details: clear dependent fields in the no-match branch instead of leaving the previous record displayed.
  • Unwanted overwrites: if users may edit the dependent fields manually, decide whether every main-field edit should replace those edits or whether the fields should become read-only.

Recommended event and data design

Decision Recommended approach Reason
Event for live autofill input Handles ongoing edits and the datalist example with one listener.
Event for commit-only behavior change Updates after the control’s value is committed rather than on every edit.
Data organization One object record per competition Keeps all four related values together and scales to many competitions.
Matching policy Normalize with trimming and lowercasing when appropriate Allows case-insensitive matches while preserving a clear key policy.
Unknown value Clear dependent fields and optionally announce a status Prevents stale data from being mistaken for a valid match.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Accessibility and form semantics

Give every control a visible label, keep the dependent values in real form controls if they must be submitted, and use an aria-live="polite" status for match errors or confirmation. If the fields are informational only, render them as text instead of disabled inputs; disabled controls are not submitted with a form. If they are derived values that users should not edit, use readOnly rather than disabled when submission is required.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.