Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <div class="widget-wrap">
  <h1>PURE JS AUTOCOMPLETE</h1>

  <!-- (A) AUTOCOMPLETE SINGLE INPUT FIELD -->
  <div class="demo">
    <label>Name:</label>
    <input type="text" id="demoA"/>
    <label>"诸葛猪哥", "Aaronn", "Baattyy", "Chaarles", "Dionn", "Elly"</label>
  </div>

  <!-- (B) AUTOCOMPLETE MULTIPLE FIELDS -->
  <div class="demo">
    <label>Name:</label>
    <input type="text" id="demoB"/>
    <label>Email:</label>
    <input type="email" id="dEmail"/>
    <label>Age:</label>
    <input type="text" id="dAge"/>
  </div>
  
  <!-- (X) VISIT CODE-BOXX -->
  <div id="code-boxx">
    Visit
    <a href="https://code-boxx.com/simple-autocomplete-html-javascript/"
       target="_blank">
      Code Boxx
    </a> for more details.
  </div>
</div>
              
            
!

CSS

              
                /* (A) AUTOCOMPLETE WRAPPER */
.acWrap {
  display: block; /* Or inline-block if you like */
  position: relative;
}

/* (B) SUGGESTIONS */
.acWrap .acSuggest {
  position: absolute;
  top: 100%; left: 0;
  z-index: 9;
  width: 100%;
  background: #fff;
  border: 1px solid #eee;
}
.acWrap .acSuggest {
  list-style: none;
  padding: 0;
  margin: 0;
}
.acWrap .acSuggest li {
  padding: 10px;
}
.acWrap .acSuggest li:hover {
  background: #d9e7ff;
  cursor: pointer;
}

/* (C) FORM */
.demo { margin-bottom: 40px; }
.demo label, .demo input {
  display: block;
  width: 100%;
}
.demo label { padding: 10px 0; }
.demo input { padding: 10px; }


/* (X) DOES NOT MATTER */
/* PAGE & BODY */
* {
  font-family: arial, sans-serif;
  box-sizing: border-box;
}
body {
  display: flex;
  align-items: center; justify-content: center;
  min-height: 100vh;
  background-image: url(https://images.unsplash.com/photo-1579546928686-286c9fbde1ec?crop=entropy&cs=srgb&fm=jpg&ixid=MnwxNDU4OXwwfDF8cmFuZG9tfHx8fHx8fHx8MTY0MTY5ODkzNQ&ixlib=rb-1.2.1&q=85);
  background-repeat: no-repeat;
  background-position: center;
  background-size: cover;
}

/* WIDGET */
.widget-wrap {
  min-width: 600px;
  padding: 30px;
  border-radius: 20px;
  background: rgba(255, 255, 255, 0.4);
}

/* FOOTER */
#code-boxx {
  font-weight: 600;
  margin-top: 50px;
}
#code-boxx a {
  display: inline-block;
  padding: 5px;
  text-decoration: none;
  background: #b90a0a;
  color: #fff;
}
              
            
!

JS

              
                var ac = {
  // (A) PROPERTIES
  now : null, // current "focused instance"

  // (B) ATTACH AUTOCOMPLETE
  //  target : target field
  //  data : suggestion data (array), or url (string)
  //  post : optional, extra data to send to server
  //  delay : optional, delay before suggestion, default 500ms
  //  min : optional, minimum characters to fire suggestion, default 2
  //  select : optional, function to call on selecting an option
  attach : inst => {
    // (B1) SET DEFAULTS
    if (inst.delay == undefined) { inst.delay = 500; }
    if (inst.min == undefined) { inst.min = 2; }
    inst.timer = null; // autosuggest timer
    inst.ajax = null; // ajax fetch abort controller

    // (B2) UPDATE HTML
    inst.target.setAttribute("autocomplete", "off");
    inst.hWrap = document.createElement("div"); // autocomplete wrapper
    inst.hList = document.createElement("ul"); // suggestion list
    inst.hWrap.className = "acWrap";
    inst.hList.className = "acSuggest";
    inst.hList.style.display = "none";
    inst.target.parentElement.insertBefore(inst.hWrap, inst.target);
    inst.hWrap.appendChild(inst.target);
    inst.hWrap.appendChild(inst.hList);

    // (B3) KEY PRESS LISTENER
    inst.target.addEventListener("keyup", evt => {
      // (B3-1) CLEAR OLD TIMER & SUGGESTION BOX
      ac.now = inst;
      if (inst.timer != null) { window.clearTimeout(inst.timer); }
      if (inst.ajax != null) { inst.ajax.abort(); }
      inst.hList.innerHTML = "";
      inst.hList.style.display = "none";

      // (B3-2) CREATE NEW TIMER - FETCH DATA FROM SERVER OR ARRAY
      if (inst.target.value.length >= inst.min) {
        if (typeof inst.data == "string") { inst.timer = setTimeout(() => ac.fetch(), inst.delay); }
        else { inst.timer = setTimeout(() => ac.filter(), inst.delay); }
      }
    });
  },

  // (C) FILTER ARRAY DATA
  filter : () => {
    // (C1) SEARCH DATA
    let search = ac.now.target.value.toLowerCase(),
        multi = typeof ac.now.data[0]=="object",
        results = [];

    // (C2) FILTER & DRAW APPLICABLE SUGGESTIONS
    for (let i of ac.now.data) {
      let entry = multi ? i.D : i ;
      if (entry.toLowerCase().includes(search)) { results.push(i); }
    }
    ac.draw(results.length==0 ? null : results);
  },

  // (D) AJAX FETCH SUGGESTIONS FROM SERVER
  fetch : () => {
    // (D1) FORM DATA
    let data = new FormData();
    data.append("search", ac.now.target.value);
    if (ac.now.post !== null) {
      for (let [k,v] of Object.entries(ac.now.post)) { data.append(k,v); }
    }

    // (D2) FETCH
    ac.now.ajax = new AbortController();
    fetch(ac.now.data, { method:"POST", body:data, signal:ac.now.ajax.signal })
    .then(res => {
      ac.now.ajax = null;
      if (res.status != 200) { throw new Error("Bad Server Response"); }
      return res.json();
    })
    .then(res => ac.draw(res))
    .catch(err => console.error(err));
  },

  // (E) DRAW AUTOSUGGESTION OPTIONS
  draw : results => { if (results == null) { ac.close(); } else {
    ac.now.hList.innerHTML = "";
    let multi = typeof results[0]=="object", entry;
    for (let i of results) {
      let row = document.createElement("li");
      row.innerHTML = multi ? i.D : i;
      if (multi) {
        entry = {...i};
        delete entry.D;
        row.dataset.multi = JSON.stringify(entry);
      }
      row.onclick = () => ac.select(row);
      ac.now.hList.appendChild(row);
    }
    ac.now.hList.style.display = "block";
  }},

  // (F) ON SELECTING A SUGGESTION
  select : row => {
    // (F1) SET VALUES
    ac.now.target.value = row.innerHTML;
    let multi = null;
    if (row.dataset.multi !== undefined) {
      multi = JSON.parse(row.dataset.multi);
      for (let i in multi) { document.getElementById(i).value = multi[i]; }
    }

    // (F2) CALL ON SELECT IF DEFINED
    if (ac.now.select != null) { ac.now.select(row.innerHTML, multi); }
    ac.close();
  },

  // (G) CLOSE AUTOCOMPLETE
  close : () => { if (ac.now != null) {
    if (ac.now.ajax != null) { ac.now.ajax.abort(); }
    if (ac.now.timer != null) { window.clearTimeout(ac.now.timer); }
    ac.now.hList.innerHTML = "";
    ac.now.hList.style.display = "none";
    ac.now = null;
  }},

  // (H) CLOSE AUTOCOMPLETE IF USER CLICKS ANYWHERE OUTSIDE
  checkclose : evt => { if (ac.now!=null && ac.now.hWrap.contains(evt.target)==false) {
    ac.close();
  }}
};
document.addEventListener("click", ac.checkclose);

/* (DEMO) AUTOCOMPLETE SINGLE FIELD */
ac.attach({
  target: document.getElementById("demoA"),
  data: ["诸葛猪哥", "Aaronn", "Baattyy", "Chaarles", "Dionn", "Elly"]
});

/* (DEMO) AUTOCOMPLETE MULTIPLE FIELDS */
ac.attach({
  target: document.getElementById("demoB"),
  data: [
    {D: "诸葛猪哥", dEmail: "zhuge@doe.com", dAge: 67 },
    {D: "Aaronn", dEmail: "aaronn@doe.com", dAge: 27 },
    {D: "Baattyy", dEmail: "baattyy@doe.com", dAge: 37 },
    {D: "Chaarles", dEmail: "chaarles@doe.com", dAge: 47 },
    {D: "Dionn", dEmail: "dionn@doe.com", dAge: 57 },
    {D: "Elly", dEmail: "elly@doe.com", dAge: 18 }
  ]
});
              
            
!
999px

Console