www.webdeveloper.com
Page 2 of 2 FirstFirst 12
Results 16 to 22 of 22

Thread: Simple auto-complete function

  1. #16
    Join Date
    Jan 2007
    Posts
    11

    Simple auto-complete function

    Hmmm. This certainly validates but to the point where it won't even let you put anything in the textField even if the name is in the array...

    Here is my .js file

    Code:
    var aName = new Array(
    
    "John Smith",
    "Harry Whodini",
    "Dill Doe",
    "Robyn Hood",
    "Andy Anderson",
    "Jimmy Johnson",
    "Chris Angel",
    "Kevin Mitnick"
    		
    );
    
    
    aName.sort();
    
    function Complete(obj, evt) {
    	 if ((!obj) || (!evt) || (aName.length == 0)) {
     	 	return;
      }
    
      if (obj.value.length == 0) {
      		return;
      }
    
      var elm = (obj.setSelectionRange) ? evt.which : evt.keyCode;
    
      if ((elm < 32) || (elm >= 33 && elm <= 46) || (elm >= 112 && elm <= 123)) {
      		return;
      }
    
      var txt = obj.value.replace(/;/gi, ",");
      elm = txt.split(",");
      txt = elm.pop();
      txt = txt.replace(/^\s*/, "");
    
      if (txt.length == 0) {
      		return;
      }
    
      if (obj.createTextRange) {
       	var rng = document.selection.createRange();
      		if (rng.parentElement() == obj) {
       			elm = rng.text;
      	 		var ini = obj.value.lastIndexOf(elm);
      		}
      } else if (obj.setSelectionRange) {
      		var ini = obj.selectionStart;
      }
    
      for (var i = 0; i < aName.length; i++) {
       	elm = aName[i].toString();
      		if (elm.toLowerCase().indexOf(txt.toLowerCase()) == 0) {
       			obj.value += elm.substring(txt.length, elm.length);
      	 		break;
      		}
      }
    
      if (obj.createTextRange) {
      		rng = obj.createTextRange();
      		rng.moveStart("character", ini);
      		rng.moveEnd("character", obj.value.length);
      		rng.select();
      } else if (obj.setSelectionRange) {
      		obj.setSelectionRange(ini, obj.value.length);
      }
    }
    function validate(inputField)
    {
    	var input = inputField.value;
    
    	for (var i in aName)
    	{
    		if (input != aName[i].toString())
    		{
    			//Alert the user that they have an invalid input.
    			//Suggestion: use another DIV element to pop up instead of an
    			//alert box, a div would actually be more user-friendly.
    			alert(input.toString() + ' is not a valid input for this field.');
    			
    			 //Resets the focus of the previous text field
    			inputField.focus();
    			
    			//Quits the function as soon as the input does not match what is in
    			//the aName array.
    			return false;
    		}
    	}
    	
    	return true;
    }
    And here is my validationTest.asp page with the form and textField:

    Code:
    <%@LANGUAGE="VBSCRIPT" CODEPAGE="1252"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Untitled Document</title>
    
    <script type="text/javascript" src="autoComplete.js"></script>
    
    </head>
    
    <body>
    
    <form action="preview.asp" method="get" name="nomineeForm" id="nomineeForm">
    <input name="nameOne" type="text" onblur="validate(this)" onkeyup="Complete(this, event)" value="Search Names" size="20" maxlength="50" autocomplete="off" />
    </FORM>
    </body>
    </html>
    Even if I type a name correctly (and it's also in the array) I still get allerted.

  2. #17
    Join Date
    Apr 2006
    Location
    Houston
    Posts
    1,374
    [Edit]
    Link to fully functional example:
    http://www.stansight.com/AutoComplete.html
    [/Edit]

    I cleaned up the syntax in my example and it seems to work:

    HTML Code:
    function ValidateComplete(obj) {
     var WeCool = false;
    
     // if input field has no value then return (Not a required field - if you want it to be required then spit out an error message)
     if (obj.value.length == 0) return true;
    
     // If input field value is found in the array then set flag to true
     for (var i = 0; i < aMail.length; i++) {
      elm = aMail[i].toString();
      if (elm == obj.value) WeCool=true;
     }
    
     // If input field value was never found then spit out an error message
     if (!WeCool) {
      alert ('Please enter a valid email value');
      obj.focus();
      obj.select();
      return false;
     }
    
     return true;
    }

    Input tag looks like this:
    HTML Code:
    <form>
     <input type="text" name="anyName" onKeyUp="Complete(this, event)" onBlur="ValidateComplete(this);">
    </form>
    Last edited by slaughters; 01-29-2007 at 03:26 PM.

  3. #18
    Join Date
    Jan 2007
    Posts
    11

    Simple auto-complete function

    Thanks Slaughters.... It works!! I just had to change aMail to aName since I was using aName as the var name...

    One question though before It's officially resolved.

    On the validator, how can I allow it to accept lowercase versions of the names in the array?

    ex:

    "John Doe" is the same as "john doe"

    I get alerted when I don't use CAPS.

    Thanks so much for your help man!

  4. #19
    Join Date
    Apr 2006
    Location
    Houston
    Posts
    1,374
    Look at the link to the fully functional example I posted in the previous message: http://www.stansight.com/AutoComplete.html

    I made the functions generic so you can pass the name of the Array to the functions instead of hard coding it. I had also changed the validation function to perform case insensitive comparisons.

  5. #20
    Join Date
    Jan 2007
    Posts
    11
    Slaughters, thank you so much Bro! I'm up and running!! Can't tell you how much I appreciate!

    Thanks again,
    Shane

  6. #21
    Join Date
    Aug 2006
    Posts
    2
    Hi everybody,

    If I understand what ShaneSwodiddy wants, I think this code can help:

    Code:
    function checkInput(element) {
       // Remove leading spaces from typed value
       var txt = element.value.replace(/^\s+|\s+$/g,"");
    
       // Check the length of value
       if (txt.length == 0) {
          alert("Any name was typed!");
          return;
       }
    
       // Ensure to transform all separators to comma
       txt = txt.replace(/;/gi, ",");
    
       // Get an array from values typed
       var elm = txt.split(",")
    
       /* elm is an array. Each element of this array
       is a name typed in from field. Use to check
       against your value array */
       var fnd;
       for (i=0; i<elm.length; i++) {
          fnd = false;
    
          for (k=0;k<aName.length;k++) {
             // Use all values to uppercase to make search
             // case insensitive
             if (elm[i].toUpperCase() == aName[k].toUpperCase()) {
                fnd = true;
                break;
             }
          }
    
          // If name was not found, alert user
          if (!fnd) {
             alert("\"" + elm[i].toString() + "\" was not found!\n\nPlease enter name correctly!");
          }
       }
    }
    ShaneSwodiddy, please, let me know if this code works for you.

    Ilanio

  7. #22
    Join Date
    Apr 2007
    Posts
    1
    Ilanio.I just want a "Add a comment, suggestion" script for my visitors.what they write is shown in the site where i put my script.And another script that again they write their names emails,and some comments,they come to my email.can u help me please??(but not with outlook express )
    Last edited by Jentzsch; 04-25-2007 at 07:09 AM.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles