The html list syntax (list="text") either fails or can’t communicate with an external javascript file

I’ve been working on my client sided searchbar for a while in javascript and i have a <datalist> with all the options in the JavaScript.
The <datalist> is inside an document.getElementById("").innerHTML. But the search bar(<input>) is inside of the html file. And i tired to use set the list syntax on the input to list="countries" which is the id of the datalist. I don’t want to put the whole datalist in every html page and the input didn’t work correctly if i put it in the javascript. It seems like they can’t comunicate if they aren’t in the same file… If anyone could help me i’d be really gratefull!

It works here because it’s not an external file.

Here is the code:

document.getElementById("search01").innerHTML =
    "<form id='search'><datalist id='countries'>" +
    "<option value='Afghanistan'>" +
    "<option value='Albania'>" +
    "</datalist></form>";

function onSearch() {
    var country;
    country = document.getElementById('bar').value;

    if (country == "Afghanistan" || country == "afghanistan") {
        window.location.href = "http://www.example.com/";
    } else if (country == "Albania" || country == "albania") {
        location.href = "http://www.example.com/";
    } else {
        document.getElementById("SearchFail01").innerHTML =
        "The country '" + country + "' does not exist";
    }
}

//check when the enter is pressed on the search bar
function keyEnter(event) {
    var key = event.keyCode || event.which;
    if (key == 13) {
        onSearch();
    } else {
        return true;
    }
}
<input type='search' id='bar' list='countries' placeholder='Search for a country..' onkeydown='keyEnter(event);' />
<p id="SearchFail01"></p>

(Im sorry if this question already exists but i couldn’t find it)


Source: syntax

Leave a Reply