How to make datalist match result from beginning only

I am tring to make datalist in html here is example

<h1>Datalist Demo</h1>
<label for="default">Pick a programming language</label>
<input type="text" id="default" list="languages">
<datalist id="languages">
    <option value="HTML">
    <option value="CSS">
    <option value="JavaScript">
    <option value="Java">
    <option value="Ruby And Go">
    <option value="PHP And HTML">
    <option value="Go">
    <option value="Erlang">
    <option value="Python And C++">
    <option value="C">
    <option value="C#">
    <option value="C++">
</datalist>

but when i search for 'go' it show me 2 results

  • Ruby And Go
  • Go

Result When i Search for 'go'

I want that it should only show term which match the beginning of entered text and NOT from inside.
Like When I search for 'go' only one result should be displayed

  • Go

I have to implement this on more than 5000 records stored in MySQL.

Answers:

Answer

For exact matches you can set pattern attribute value dynamically to RegExp [\\w\\s+#]{${this.value.length}} at input event

<h1>Datalist Demo</h1>
<label for="default">Pick a programming language</label>
<input type="text" id="default" list="languages" pattern="">
<datalist id="languages">
    <option value="HTML">
    <option value="CSS">
    <option value="JavaScript">
    <option value="Java">
    <option value="Ruby And Go">
    <option value="PHP And HTML">
    <option value="Go">
    <option value="Erlang">
    <option value="Python And C++">
    <option value="C">
    <option value="C#">
    <option value="C++">
</datalist>
<script>
  document.querySelector("#default")
  .oninput = function() {
    this.pattern = `[\\w\\s+#]{${this.value.length}}`;
  }
</script>

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.