Andy's Net

Autofill an Input

Making those really complex input forms so much easier!

Input Autofill

The Code

// Get our JSON data.
(async function(){
    const countries = [],
          input = document.getElementById( 'autofillInput' );

    await fetch( 'https://raw.githubusercontent.com/annexare/Countries/master/dist/countries.json' )
                .then( response => response.json() )
                .then( json => {
                    countries.push( ...Object.values( json ) );
                } );

    // Listen for changes!
    input.addEventListener( 'keyup', checkInput, true );

    // Check the input against our countries array.
    function checkInput(){

        // Loop through and remove all current elements.
        const allOptions = document.querySelectorAll( '.autofillOption' );
        allOptions.forEach( element => {
            element.remove();
        } );
        
        const typed = input.value.toLowerCase();

        const filtered = countries.filter( country => ( country.name.toLowerCase().includes( typed ) || country.native.toLowerCase().includes( typed ) ) );
        
        if ( typed.length === 0 ){
            return;
        }

        filtered.forEach( country => displayInformation( country ) );

    }

    function displayInformation( country ){

        const div = document.createElement( 'div' );

        div.className = 'autofillOption';
        div.innerHTML = `${country.name}
Captial: ${country.capital} | Currency: ${country.currency}
`; div.dataset.value = country.name; input.parentNode.appendChild( div ); // Add click event listener. div.addEventListener( 'click', event => { handleClick( div ); } ); } function handleClick( div ){ const value = div.dataset.value; input.value = value; checkInput(); } checkInput(); })();