Search code examples
javascripthtmlkeypressonkeypress

How to autofill a text field when pressing a key


So I have a requirement where I need to type something and then halfway through, it should automatically fill the rest of the things.

Example

I have a Text Field, where I start to type "col" then after I press space the text field should show me "column", auto for the auto-correct system.

Also, I was wondering if this could be implemented as an array or a column of data coming from my DB?

I made something like this, but this changes values of an innerHTML field. I need this for the text field itself.

function handle(e) {
  if (e.keyCode === 32) {
        e.preventDefault();
        document.getElementById("p1").innerHTML = "Column";
    }
}
<p id="p1">Hello World!</p>
<form action="#">
    <input type="text" name="txt" onkeypress="handle(event)" />
</form>

I'm new to this so any help would be deeply appreciated


Solution

  • Load your values from your database in a JSON and use the e.target property that will contain the HTML element where the event occurred.

    Try the following code:

    // load your values from DB here
    var dictionary = {
      'col': 'Column',
      'ro': 'Row',
      'tab': 'Table'
    };
    
    function handle(e) {
      if (e.keyCode === 32) {
        e.preventDefault();
    
        for (val in dictionary) {
          if (e.target.value == val) {
            e.target.value = dictionary[val];
            continue;
          }
        }
      }
    }
    <p id="p1">Hello World!</p>
    <form action="#">
      <input type="text" name="txt" onkeypress="handle(event)" />
    </form>