0

I am trying to create a search using JavaScript. I have created the framework, but not sure how to make it that when the user clicks on a dropdown item, it populates the input field with the selected option. What should I do? Here's my code:

HTML:

<input class="form-control searchResult" type="text" id="search" placeholder="Search">

<div id="match-list"></div>

JS:

const search = document.getElementById('search');
const matchList = document.getElementById('match-list');

const searchStates = async searchText => {
    const res = await fetch('countries.json');
    const states = await res.json();

    let matches = states.filter(state => {
        const regex = new RegExp(`^${searchText}`, 'gi');
        return state.name.match(regex);
    })

    if (searchText.length === 0) {
        matches = [];
        matchList.innerHTML = '';
    }

    if (matches.length > 0) {
        const html = matches.map((match, i) => `<div class="dropdown" id="dropdown${i}"><option class="dropdown-text" id="dropdown-text${i}">${match.name}</option></div>`).join('');

        console.log(html);
        matchList.innerHTML = HTML;
    }

}

search.addEventListener('input', () => searchStates(search.value));

JSON:

[
  {
  "name":"Afghanistan",
  "phoneCode":"+93",
  "capital":"Kabul",
  "abbr":"AFG"
  },
  {
  "name":"Albania",
  "phoneCode":"+355",
  "capital":"Tirana",
  "abbr":"ALB"
  },
  {
  "name":"Algeria",
  "phoneCode":"+213",
  "capital":"Algiers",
  "abbr":"DZA"
  }
]
3

1 Answer 1

1

You might be better off using the datalist tag. This will directly filter the results and react to click events:

html:

<input id="country-input list="countries">
<datalist id="countries"></datalist>
<button onClick="send">Send</button>

js:

// Store countries array in COUNTRIES
const inputDataList = document.getElementById("countries");

COUNTRIES.forEach((country) => {
  const countryOption = document.createElement("option");
  countryOption.value = country.name;
  inputDataList.appendChild(countryOption);
});

To read the input value, just get the .value from the input element:

const countryInput = document.getElementById("country-input");

const sendCountry = () => {
    // Do stuff with countryInput.value
    console.log(countryInput.value);
};
Sign up to request clarification or add additional context in comments.

2 Comments

That definitely works and I have implemented that. So now, in order to get what the user selected, I have to grab the value of the <datalist> tag, correct? Or would I grab the value of the <input> tag?
You would grab the value of the input tag. I've edited my answer ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.