{"id":28753,"date":"2024-04-18T21:24:02","date_gmt":"2024-04-18T20:24:02","guid":{"rendered":"https:\/\/nelkodev.com\/blog\/domina-el-autocompletado-en-formularios-con-javascript-puro\/"},"modified":"2024-06-03T18:44:04","modified_gmt":"2024-06-03T17:44:04","slug":"domina-el-autocompletado-en-formularios-con-javascript-puro","status":"publish","type":"post","link":"https:\/\/nelkodev.com\/en\/blog\/master-form-autocompletion-with-pure-javascript\/","title":{"rendered":"Master Form Autocompletion with Pure JavaScript"},"content":{"rendered":"<p>In today&#039;s digital age, user experience on the web is crucial to the success of any project. One of the features that significantly improves this experience in web forms is autocomplete. This functionality not only streamlines the data filling process, but also improves the accuracy of the information entered. In this guide I will show you how to implement an autocomplete system using only JavaScript, without depending on additional libraries.<\/p>\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_80 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><a href=\"#\" class=\"ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle\" aria-label=\"Toggle Table of Content\"><span class=\"ez-toc-js-icon-con\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #ffffff;color:#ffffff\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewbox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #ffffff;color:#ffffff\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewbox=\"0 0 24 24\" version=\"1.2\" baseprofile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/span><\/a><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-form-autocompletion-with-pure-javascript\/#%C2%BFQue_es_una_Funcion_de_Autocompletado\" >What is an AutoComplete Function?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-form-autocompletion-with-pure-javascript\/#Pasos_Iniciales_Preparando_tu_Proyecto\" >Initial Steps: Preparing your Project<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-form-autocompletion-with-pure-javascript\/#Estructura_Inicial_de_tu_HTML\" >Initial structure of your HTML<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-form-autocompletion-with-pure-javascript\/#Implementando_el_Autocompletado_con_JavaScript\" >Implementing AutoComplete with JavaScript<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-form-autocompletion-with-pure-javascript\/#Paso_1_Crear_la_Funcion_Base\" >Step 1: Create the Base Function<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-form-autocompletion-with-pure-javascript\/#Paso_2_Mostrar_Sugerencias\" >Step 2: Show Suggestions<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-form-autocompletion-with-pure-javascript\/#Paso_3_Estilizando_el_Autocompletado\" >Step 3: Styling AutoFill<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-form-autocompletion-with-pure-javascript\/#Conclusion\" >Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<h2><span class=\"ez-toc-section\" id=\"%C2%BFQue_es_una_Funcion_de_Autocompletado\"><\/span>What is an AutoComplete Function?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Autocomplete is a user interface feature that predicts the rest of a word or phrase as the user begins typing in a form field. This not only speeds up data entry, but also helps avoid typing errors and improves usability.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Pasos_Iniciales_Preparando_tu_Proyecto\"><\/span>Initial Steps: Preparing your Project<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Before we dive into the code, make sure you have a suitable environment for development. You will need the following:<\/p>\n<ol>\n<li><strong>Code Editor:<\/strong> You can use editors like VSCode or Sublime Text.<\/li>\n<li><strong>Modern Browser:<\/strong> Chrome, Firefox or any browser that supports modern JavaScript.<\/li>\n<li><strong>Development console:<\/strong> Accessible in most browsers to test and debug your code.<\/li>\n<\/ol>\n<p>Once you have everything ready, create a new folder for your project and inside, a file called <code>index.html<\/code> and another call <code>script.js<\/code>.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Estructura_Inicial_de_tu_HTML\"><\/span>Initial structure of your HTML<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Next, we will build the basic structure of your file <code>index.html<\/code>. Here is an initial example:<\/p>\n<pre><code class=\"&quot;language-html&quot;\">&lt;!DOCTYPE html&gt;\n&lt;html lang=&quot;es&quot;&gt;\n&lt;head&gt;\n    &lt;meta charset=&quot;UTF-8&quot;&gt;\n    &lt;title&gt;Autocomplete Form&lt;\/title&gt;\n    &lt;link rel=&quot;stylesheet&quot; href=&quot;styles.css&quot;&gt;\n&lt;\/head&gt;\n&lt;body&gt;\n    &lt;div class=&quot;autocomplete-container&quot;&gt;\n        &lt;input id=&quot;autocomplete-input&quot; type=&quot;text&quot; placeholder=&quot;Write something...&quot;&gt;\n    &lt;\/div&gt;\n    &lt;script src=&quot;script.js&quot;&gt;&lt;\/script&gt;\n&lt;\/body&gt;\n&lt;\/html&gt;<\/code><\/pre>\n<p>Make sure the JS script is loaded at the end of the body so that all HTML content is available before the JavaScript tries to access it.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Implementando_el_Autocompletado_con_JavaScript\"><\/span>Implementing AutoComplete with JavaScript<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<h3><span class=\"ez-toc-section\" id=\"Paso_1_Crear_la_Funcion_Base\"><\/span>Step 1: Create the Base Function<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>in your file <code>script.js<\/code>, let&#039;s start by developing a function that listens to each key pressed in the input and starts filtering suggestions based on the user&#039;s input.<\/p>\n<pre><code class=\"&quot;language-javascript&quot;\">document.addEventListener(&#039;DOMContentLoaded&#039;, function() { const inputData = [&quot;Apple&quot;, &quot;Banana&quot;, &quot;Cherry&quot;, &quot;Date&quot;, &quot;Fig&quot;, &quot;Grape&quot;, &quot;Lemon&quot;]; const inputField = document .getElementById(&#039;autocomplete-input&#039;); inputField.addEventListener(&#039;input&#039;, function() { let input = this.value; if (!input) { clearSuggestions(); return; } let suggestions = getMatches(inputData , input); showSuggestions(suggestions, this); function getMatches(data, input) { let matches = []; let regex = new RegExp(`${input}`, &#039;i&#039;); \/\/ &#039;i&#039; to ignore case for (let i = 0; i &lt; data.length; i++) { if (data[i].match(regex)) { matches.push(data[i]); } } return matches; }<\/code><\/pre>\n<h3><span class=\"ez-toc-section\" id=\"Paso_2_Mostrar_Sugerencias\"><\/span>Step 2: Show Suggestions<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>The function <code>display suggestions()<\/code> will manipulate the DOM to display the possible hints under the input field:<\/p>\n<pre><code class=\"&quot;language-javascript&quot;\">function showSuggestions(suggestions, inputField) { clearSuggestions(); let suggestionBox = document.createElement(&#039;div&#039;); suggestionBox.id = &#039;suggestion-box&#039;; inputField.parentNode.appendChild(suggestionBox); suggestions.forEach(function(item) { let div = document.createElement(&#039;div&#039;); div.innerHTML = item; div.addEventListener(&#039;click&#039;, function() { inputField.value = this.innerText; clearSuggestions (); }); suggestionBox.appendChild(div); } function clearSuggestions() { const existingBox = document.getElementById(&#039;suggestion-box&#039;); if (existingBox) { existingBox.parentNode.removeChild(existingBox); } }<\/code><\/pre>\n<h3><span class=\"ez-toc-section\" id=\"Paso_3_Estilizando_el_Autocompletado\"><\/span>Step 3: Styling AutoFill<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Add the file <code>styles.css<\/code> to visually enhance suggestions and ensure users have a good visual and functional experience.<\/p>\n<pre><code class=\"&quot;language-css&quot;\">.autocomplete-container { position: relative; width: 300px; margin: 0 self; } #suggestion-box { position: absolute; background: white; width: 100%; border: 1px solid #ccc; } #suggestion-box div { padding: 8px; cursor: pointer; } #suggestion-box div:hover { background-color: #f0f0f0; }<\/code><\/pre>\n<h2><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Implementing an autocomplete function in your web forms may seem complex, but with a little JavaScript, it is perfectly possible to do it without dependency on external libraries. Now that you have a basic autocomplete feature, you can adapt and enhance it to fit the specific needs of your web projects.<\/p>\n<p>If you want to delve deeper into JavaScript or have any questions, feel free to visit <a href=\"https:\/\/nelkodev.com\/en\/\">my blog<\/a> or contact me through <a href=\"https:\/\/nelkodev.com\/en\/contact\/\">my contact page<\/a>. I&#039;m here to help you on your path to web development mastery.<\/p>\n<p>Happy coding!<\/p>","protected":false},"excerpt":{"rendered":"<p>In today\u2019s digital age, user experience on the web is crucial to the success of any project. One of the features that significantly improve this experience in web forms is auto-completion. This functionality not only speeds up the data filling process, but also improves the accuracy of the form.<\/p>","protected":false},"author":1,"featured_media":28754,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[420,2207,1901],"tags":[1476,205,90,1473,492,185,2208,627,1008,1825],"class_list":["post-28753","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-blog","category-nodejs","category-pruebas-de-proyecto","tag-autocompletado","tag-blog","tag-con","tag-domina","tag-formularios","tag-javascript","tag-nodejs","tag-proyecto","tag-pruebas","tag-puro"],"_links":{"self":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/posts\/28753","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/comments?post=28753"}],"version-history":[{"count":0,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/posts\/28753\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/media\/28754"}],"wp:attachment":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/media?parent=28753"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/categories?post=28753"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/tags?post=28753"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}