Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 13 of 13
  1. #1
    Regular Coder
    Join Date
    Nov 2010
    Posts
    390
    Thanks
    48
    Thanked 1 Time in 1 Post

    Question JavaScript? Predictive Text for Form Field Input?

    Hello,

    I am in the process of making a large, multi-step form and would like to implement predictive text on on or more text input fields.

    Alike the Google and YouTube search engine, it will highlight the words and phrases like this:

    Search box: lan
    predictive text:
    • Lancaster
    • England
    • Finland
    • Scotland


    The example above was for if the field was for example 'Where are you'.

    I have tried researching, however, the outcomes are for a much larger search using databases, I just want to do a small predictive text for form field input.

    Thank you for any help and/or advice in advanced.

    Best Regards,
    Tim

  • #2
    Regular Coder
    Join Date
    Apr 2012
    Location
    St. Louis, MO
    Posts
    985
    Thanks
    7
    Thanked 101 Times in 101 Posts
    Typically this would be done with a database, yes. I suppose you _could_ use a text file or xml file and get the same results, but the file would be HUGE. Better off using a database, IMHO.
    ^_^

    If anyone knows of a website that can offer ColdFusion help that isn't controlled by neurotic, pedantic jerks* (stackoverflow.com), please PM me with a link.
    *
    The neurotic, pedantic jerks are not the owners; just the people who are in control of the "popularity contest".

  • #3
    Regular Coder
    Join Date
    Nov 2010
    Posts
    390
    Thanks
    48
    Thanked 1 Time in 1 Post
    Quote Originally Posted by WolfShade View Post
    Typically this would be done with a database, yes. I suppose you _could_ use a text file or xml file and get the same results, but the file would be HUGE. Better off using a database, IMHO.
    The are only a maximum of 30 words for the predictive text to output, this would be a waste of a database.

    There's surely a simple way to do this...

  • #4
    Regular Coder
    Join Date
    Apr 2012
    Location
    St. Louis, MO
    Posts
    985
    Thanks
    7
    Thanked 101 Times in 101 Posts
    Well, if there are only thirty words, then that's different.

    Basically it would be set up the same way as if it were a database, just use the file as the "source" instead of a database. Put each word on a separate line and make an array out of it using the CRLF as the delimiter, then search the array with every keyUp and display the results.
    ^_^

    If anyone knows of a website that can offer ColdFusion help that isn't controlled by neurotic, pedantic jerks* (stackoverflow.com), please PM me with a link.
    *
    The neurotic, pedantic jerks are not the owners; just the people who are in control of the "popularity contest".

  • #5
    Regular Coder
    Join Date
    Nov 2010
    Posts
    390
    Thanks
    48
    Thanked 1 Time in 1 Post
    Quote Originally Posted by WolfShade View Post
    Well, if there are only thirty words, then that's different.

    Basically it would be set up the same way as if it were a database, just use the file as the "source" instead of a database. Put each word on a separate line and make an array out of it using the CRLF as the delimiter, then search the array with every keyUp and display the results.
    I'm a newbie in JavaScript so if you have the time, could you please explain yourself a little more clearer?

    My friend suggested this and I added the values in, however I do not kno whow to use this...

    Code:
    <script language="javascript">
    	var places = ["Dump","Auction","Waling round the city","Big Al\'s Gun Shop","Sally\'s Sweet Shop","TC Clothing","Bits /'n/' Bobs","Jewelry Shop","Torn Super Store","Cyber Force","Torn City Docks","Post Office","Pawn Shop","Mexico / Ciudad Juárez","Canada / Toronto","Cayman Islands - George Town","Hawaii - Honolulu","United Kingdom - London","Switzerland - Zurich","Argentina - Buenos Aires","Japan - Tokyo","China - Beijing","UAE \- Dubai","South Africa - Johannesburg"];
    	$('your select field here').keydown(function() {var sugg = [];
    	var reg = new RegExp($(this).val());
    	for (var i = 0; i < places.length; i++) {
    	if (reg.test(places[i])) sugg.push(places[i]);
    	}
    	if (sugg.length == 0) sugg.push('No matches found');
    	//do something with your sugg array here! put it into a dropdown somewhere... etc
    	});
    </script>
    Best Regards,
    Tim

  • #6
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,193
    Thanks
    75
    Thanked 4,341 Times in 4,307 Posts
    Well, Google cheats. The thing they use that *LOOKS* like it is a simple <input type="text"> box is not. It's actually a <span> or <div> that they style to look the same. It's the only way you can highlight WITHIN what the user typed in.

    But if you don't need that...if it's okay if just the *suggestions* get the highlighting, then it's not too hard. That harder part comes in allowing people to choose one of the suggestions. Assuming that's what you want to allow. Again, Google cheats. If you are willing to simply show the list of suggestions, with your highlighting, and then allow the user to CLICK on one to select it, then it's pretty easy.

    Is that sufficient?
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #7
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,193
    Thanks
    75
    Thanked 4,341 Times in 4,307 Posts
    Forgot to mention: And the CHEAT that Google uses requires a *TON* of JavaScript code. I've come close, but I haven't quite duplicated it yet. None of it is truly HARD code, but there has to be so much of it.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #8
    Regular Coder
    Join Date
    Nov 2010
    Posts
    390
    Thanks
    48
    Thanked 1 Time in 1 Post
    Quote Originally Posted by Old Pedant View Post
    Well, Google cheats. The thing they use that *LOOKS* like it is a simple <input type="text"> box is not. It's actually a <span> or <div> that they style to look the same. It's the only way you can highlight WITHIN what the user typed in.

    But if you don't need that...if it's okay if just the *suggestions* get the highlighting, then it's not too hard. That harder part comes in allowing people to choose one of the suggestions. Assuming that's what you want to allow. Again, Google cheats. If you are willing to simply show the list of suggestions, with your highlighting, and then allow the user to CLICK on one to select it, then it's pretty easy.

    Is that sufficient?
    Quote Originally Posted by Old Pedant View Post
    Forgot to mention: And the CHEAT that Google uses requires a *TON* of JavaScript code. I've come close, but I haven't quite duplicated it yet. None of it is truly HARD code, but there has to be so much of it.
    It doesn't have to highlight, I just thought it would be a simple thing to do, however I have been searching for the past few hours with no luck.

    I just want something that is simple, looks okay and includes my words if they type in the text input field.

    Thank you for your reply.

    Best Regards,
    Tim

  • #9
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,193
    Thanks
    75
    Thanked 4,341 Times in 4,307 Posts
    Okay...here goes... Not sure it's exactly what you wanted, but ...

    Try typing "L" first, then "A", and then "T". Then backspace and "N".

    And then use the mouse to click on one of the choices.

    Code:
    <!DOCTYPE html>
    <html>
    <head>
    <style type="text/css">
    .searchField {
        width: 200px;
    }
    #results {
        display: none;
        position: absolute;
        width: 200px;
        background-color: lightyellow; 
        z-index: 10;
    }
    #results div {
        position: absolute;
        width: 200px; 
        height: 20px;
        background-color: lightblue; 
        cursor: pointer;
    }
    #results div span {
        color: red;
        font-weight: bold;
    }
    </style>
    <body>
    <form id="theForm">
    Search for: <input name="search" class="searchField"/>
    </form>
    Here is some text.<br/>
    Here is some text.<br/>
    Here is some text.<br/>
    Here is some text.<br/>
    Here is some text.<br/>
    
    <div id="results"></div>
    
    <script type="text/javascript">
    (
      function()
      {
    
          var lookFor = [
              "Lancaster",
              "England",
              "Finland",
              "Scotland",
              "Brazil",
              "Manila",
              "Atlanta"
          ];
    
          var form = document.getElementById("theForm");
          var resultsDiv = document.getElementById("results");
          var searchField = form.search;
    
          // first, position the results:
          var node = searchField;
          var x = 0;
          var y = 0;
          while ( node != null )
          {
              x += node.offsetLeft;
              y += node.offsetTop;
              node = node.offsetParent;
          }
          resultsDiv.style.left = x + "px";
          resultsDiv.style.top  = (y + 20) + "px";
          
          // now, attach the keyup handler to the search field:
          searchField.onkeyup = function()
          {
              var txt = this.value.toLowerCase();
              if ( txt.length == 0 ) return;
    
              var txtRE = new RegExp( "(" + txt + ")", "ig" );
              // now...do we have any matches?
              var top = 0;
              for ( var s = 0; s < lookFor.length; ++s )
              {
                  var srch = lookFor[s];
                  if ( srch.toLowerCase().indexOf(txt) >= 0 )
                  {
                      srch = srch.replace( txtRE, "<span>$1</span>" );
                      var div = document.createElement("div");
                      div.innerHTML = srch;
                      div.onclick = function() {
                          searchField.value = this.innerHTML.replace(/\<\/?span\>/ig,"");
                          resultsDiv.style.display = "none";
                      };
                      div.style.top = top + "px";
                      top += 20;
                      resultsDiv.appendChild(div);
                      resultsDiv.style.display = "block";
                  }
              }
          }
          // and the keydown handler:
          searchField.onkeydown = function() 
          {
              while ( resultsDiv.firstChild != null )
              {
                  resultsDiv.removeChild( resultsDiv.firstChild );          
              }
              resultsDiv.style.display = "none";
          }
         
      }
    )();
    </script>
    </body>
    </html>
    Last edited by Old Pedant; 07-13-2012 at 11:59 PM.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    MrTIMarshall (07-13-2012)

  • #10
    Regular Coder
    Join Date
    Nov 2010
    Posts
    390
    Thanks
    48
    Thanked 1 Time in 1 Post
    Quote Originally Posted by Old Pedant View Post
    Okay...here goes... Not sure it's exactly what you wanted, but ...

    Try typing "L" first, then "A", and then "T". Then backspace and "N".

    And then use the mouse to click on one of the choices.


    Code:
    <!DOCTYPE html>
    <html>
    <head>
    <style type="text/css">
    .searchField {
        width: 200px;
    }
    #results {
        display: none;
        position: absolute;
        width: 200px;
    }
    #results div {
        position: absolute;
        width: 200px; 
        height: 20px;
        cursor: pointer;
    }
    #results div span {
        color: red;
        font-weight: bold;
    }
    </style>
    <body>
    <form id="theForm">
    Search for: <input name="search" class="searchField"/>
    </form>
    <div id="results"></div>
    
    <script type="text/javascript">
    (
      function()
      {
    
          var lookFor = [
              "Lancaster",
              "England",
              "Finland",
              "Scotland",
              "Brazil",
              "Manila",
              "Atlanta"
          ];
    
          var form = document.getElementById("theForm");
          var resultsDiv = document.getElementById("results");
          var searchField = form.search;
    
          // first, position the results:
          var node = searchField;
          var x = 0;
          var y = 0;
          while ( node != null )
          {
              x += node.offsetLeft;
              y += node.offsetTop;
              node = node.offsetParent;
          }
          resultsDiv.style.left = x + "px";
          resultsDiv.style.top  = (y + 20) + "px";
          
          // now, attach the keyup handler to the search field:
          searchField.onkeyup = function()
          {
              var txt = this.value.toLowerCase();
              if ( txt.length == 0 ) return;
    
              var txtRE = new RegExp( "(" + txt + ")", "ig" );
              // now...do we have any matches?
              var top = 0;
              for ( var s = 0; s < lookFor.length; ++s )
              {
                  var srch = lookFor[s];
                  if ( srch.toLowerCase().indexOf(txt) >= 0 )
                  {
                      srch = srch.replace( txtRE, "<span>$1</span>" );
                      var div = document.createElement("div");
                      div.innerHTML = srch;
                      div.onclick = function() {
                          searchField.value = this.innerHTML.replace(/\<\/?span\>/ig,"");
                          resultsDiv.style.display = "none";
                      };
                      div.style.top = top + "px";
                      top += 20;
                      resultsDiv.appendChild(div);
                      resultsDiv.style.display = "block";
                  }
              }
          }
          // and the keydown handler:
          searchField.onkeydown = function() 
          {
              while ( resultsDiv.firstChild != null )
              {
                  resultsDiv.removeChild( resultsDiv.firstChild );          
              }
              resultsDiv.style.display = "none";
          }
         
      }
    )();
    </script>
    </body>
    </html>
    Thank you very much! This is PERFECT!

    I appreciate the time and effort you have put in to helping me.

    Best Regards,
    Tim

  • #11
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,193
    Thanks
    75
    Thanked 4,341 Times in 4,307 Posts
    I just changed it a little bit. Needed to have a z-index and a background color to hide stuff that would be below the search box when the dropdown list appears.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #12
    Regular Coder
    Join Date
    Nov 2010
    Posts
    390
    Thanks
    48
    Thanked 1 Time in 1 Post
    You wouldn't happen to know how to turn off the browsers history on this field so there's not two boxes open at a time?

    Best Regards,
    Tim

  • #13
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,193
    Thanks
    75
    Thanked 4,341 Times in 4,307 Posts
    Code:
    <input name="search" class="searchField" autocomplete="off" />
    Good catch. Forgot about that.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    MrTIMarshall (07-14-2012)


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •