javascriptsearchtext-search

I'm having trouble with a simple search form with javascript


I know what I'm stuck with is simple.

My example is here: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_filter_list

I want to do the opposite. Nothing appears at first. They start appearing as you type the 2nd or 3rd letter in the search form. Wouldn't that be great?

Thank you for your help.


Solution

  • There's a couple approaches you can consider, for now I can show you a solution that only edits your current code slightly.

    To better tell you what lines I've changed, I've moved your code over to a JSfiddle.

    https://jsfiddle.net/ubLve2hx/1/

    I've edited your code to fit the functionality you describe, it starts showing the list once you've typed 2 characters or more.

    The first change is at line 5 of the HTML section;

    <ul id="myUL" style="display: none;">
    

    We've made it so your list isn't visible to begin with.

    Then at the javascript section, line 8 to 12 we've added the following;

    if (filter.length > 1) {
      ul.style.display = "block";
    } else {
      ul.style.display = "none";
    }
    

    So if your filter has more than 1 character, show the list, else hide the list.

    I hope this has helped! If you want I can show you some approaches on how to better structure search lists like this.