Autofill form fields, almost working

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • bonneylake
    Contributor
    • Aug 2008
    • 769

    Autofill form fields, almost working

    Hey Everyone,

    Well after asking many questions i have this almost working.

    This is how it works. Basically i fill in my customer number field an that populates my drop down box. Once i select an option from the drop down box it populates the rest of the form. The problem i am having is that if a customer number doesn't exist in the drop down box an i try to put a new customer number in the input say 538 an then click on another field such as first name i get an error saying Object expected. An well i can't figure out why its saying that. An could really use some help as to why i am getting this error.

    i started a topic earlier about this which you can see here. don't know if this will help in anyway but thought i would post it anyway.


    here is my form
    Code:
    Customer Number*:<input type="text" name="custnum" id="clientID" value=""  ONKEYUP="autoComplete(this,this.form.options,'value',false)"  onChange="validate(this.form.custnum,'Customer Number')"/>
    <SELECT NAME="options" id="options"
    onChange="this.form.custnum.value=this.options[this.selectedIndex].value;javascript:initFormEvents();">
    <cfoutput query="getcustnum">
    <option value="#fk_custNum#">#fk_custNum#</option>
    </cfoutput>
    </SELECT>
    First name: <input type="text" name="fname" id="fname" value="" size="20"/>
    here is the javascript that appears on my form.
    Code:
    <SCRIPT LANGUAGE="JavaScript" SRC="autocomplete.js"></SCRIPT>
    	<script type="text/javascript" src="ajax.js"></script>
    	<script type="text/javascript">
    
    var ajax = new sack();
    	var currentClientID=false;
    	function getClientData()
    	{
    		var clientId = document.getElementById('clientID').value;
    			currentClientID = clientId
    			ajax.requestFile = 'getClient.cfm?custnum='+clientId;	// Specifying which file to get
    			ajax.onCompletion = showClientData;	// Specify function that will be executed after file has been found
    			ajax.runAJAX();		// Execute AJAX function			
    		
    	}
    	
    	function showClientData()
    	{
    		var formObj = document.forms['page1'];	
    		eval(ajax.response);
    	}
    	
    	
    	function initFormEvents()
    	{
    		document.getElementById("options").onchange = getClientData;
    	}
    	
    	window.onload = initFormEvents;
    	</script>
    heres whats on my autocomplete.js file
    Code:
    function autoComplete (field, select, property, forcematch) {
    	var found = false;
    	for (var i = 0; i < select.options.length; i++) {
    	if (select.options[i][property].toUpperCase().indexOf(field.value.toUpperCase()) == 0) {
    		found=true; break;
    		}
    	}
    	if (found) { select.selectedIndex = i; }
    	else { select.selectedIndex = -1; }
    	if (field.createTextRange) {
    		if (forcematch && !found) {
    			field.value=field.value.substring(0,field.value.length-1); 
    			return;
    			}
    		var cursorKeys ="8;46;37;38;39;40;33;34;35;36;45;";
    		if (cursorKeys.indexOf(event.keyCode+";") == -1) {
    			var r1 = field.createTextRange();
    			var oldValue = r1.text;
    			var newValue = found ? select.options[i][property] : oldValue;
    			if (newValue != field.value) {
    				field.value = newValue;
    				var rNew = field.createTextRange();
    				rNew.moveStart('character', oldValue.length) ;
    				rNew.select();
    				}
    			}
    		}
    	}
    here what appears on my ajax.js file

    Code:
    function sack(file) {
    	this.xmlhttp = null;
    
    	this.resetData = function() {
    		this.method = "POST";
      		this.queryStringSeparator = "?";
    		this.argumentSeparator = "&";
    		this.URLString = "";
    		this.encodeURIString = true;
      		this.execute = false;
      		this.element = null;
    		this.elementObj = null;
    		this.requestFile = file;
    		this.vars = new Object();
    		this.responseStatus = new Array(2);
      	};
    
    	this.resetFunctions = function() {
      		this.onLoading = function() { };
      		this.onLoaded = function() { };
      		this.onInteractive = function() { };
      		this.onCompletion = function() { };
      		this.onError = function() { };
    		this.onFail = function() { };
    	};
    
    	this.reset = function() {
    		this.resetFunctions();
    		this.resetData();
    	};
    
    	this.createAJAX = function() {
    		try {
    			this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    		} catch (e1) {
    			try {
    				this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    			} catch (e2) {
    				this.xmlhttp = null;
    			}
    		}
    
    		if (! this.xmlhttp) {
    			if (typeof XMLHttpRequest != "undefined") {
    				this.xmlhttp = new XMLHttpRequest();
    			} else {
    				this.failed = true;
    			}
    		}
    	};
    
    	this.setVar = function(name, value){
    		this.vars[name] = Array(value, false);
    	};
    
    	this.encVar = function(name, value, returnvars) {
    		if (true == returnvars) {
    			return Array(encodeURIComponent(name), encodeURIComponent(value));
    		} else {
    			this.vars[encodeURIComponent(name)] = Array(encodeURIComponent(value), true);
    		}
    	}
    
    	this.processURLString = function(string, encode) {
    		encoded = encodeURIComponent(this.argumentSeparator);
    		regexp = new RegExp(this.argumentSeparator + "|" + encoded);
    		varArray = string.split(regexp);
    		for (i = 0; i < varArray.length; i++){
    			urlVars = varArray[i].split("=");
    			if (true == encode){
    				this.encVar(urlVars[0], urlVars[1]);
    			} else {
    				this.setVar(urlVars[0], urlVars[1]);
    			}
    		}
    	}
    
    	this.createURLString = function(urlstring) {
    		if (this.encodeURIString && this.URLString.length) {
    			this.processURLString(this.URLString, true);
    		}
    
    		if (urlstring) {
    			if (this.URLString.length) {
    				this.URLString += this.argumentSeparator + urlstring;
    			} else {
    				this.URLString = urlstring;
    			}
    		}
    
    		// prevents caching of URLString
    		this.setVar("rndval", new Date().getTime());
    
    		urlstringtemp = new Array();
    		for (key in this.vars) {
    			if (false == this.vars[key][1] && true == this.encodeURIString) {
    				encoded = this.encVar(key, this.vars[key][0], true);
    				delete this.vars[key];
    				this.vars[encoded[0]] = Array(encoded[1], true);
    				key = encoded[0];
    			}
    
    			urlstringtemp[urlstringtemp.length] = key + "=" + this.vars[key][0];
    		}
    		if (urlstring){
    			this.URLString += this.argumentSeparator + urlstringtemp.join(this.argumentSeparator);
    		} else {
    			this.URLString += urlstringtemp.join(this.argumentSeparator);
    		}
    	}
    
    	this.runResponse = function() {
    		eval(this.response);
    	}
    
    	this.runAJAX = function(urlstring) {
    		if (this.failed) {
    			this.onFail();
    		} else {
    			this.createURLString(urlstring);
    			if (this.element) {
    				this.elementObj = document.getElementById(this.element);
    			}
    			if (this.xmlhttp) {
    				var self = this;
    				if (this.method == "GET") {
    					totalurlstring = this.requestFile + this.queryStringSeparator + this.URLString;
    					this.xmlhttp.open(this.method, totalurlstring, true);
    				} else {
    					this.xmlhttp.open(this.method, this.requestFile, true);
    					try {
    						this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
    					} catch (e) { }
    				}
    
    				this.xmlhttp.onreadystatechange = function() {
    					switch (self.xmlhttp.readyState) {
    						case 1:
    							self.onLoading();
    							break;
    						case 2:
    							self.onLoaded();
    							break;
    
    						case 3:
    							self.onInteractive();
    							break;
    						case 4:
    							self.response = self.xmlhttp.responseText;
    							self.responseXML = self.xmlhttp.responseXML;
    							self.responseStatus[0] = self.xmlhttp.status;
    							self.responseStatus[1] = self.xmlhttp.statusText;
    
    							if (self.execute) {
    								self.runResponse();
    							}
    
    							if (self.elementObj) {
    								elemNodeName = self.elementObj.nodeName;
    								elemNodeName.toLowerCase();
    								if (elemNodeName == "input"
    								|| elemNodeName == "select"
    								|| elemNodeName == "option"
    								|| elemNodeName == "textarea") {
    									self.elementObj.value = self.response;
    								} else {
    									self.elementObj.innerHTML = self.response;
    								}
    							}
    							if (self.responseStatus[0] == "200") {
    								self.onCompletion();
    							} else {
    								self.onError();
    							}
    
    							self.URLString = "";
    							break;
    					}
    				};
    
    				this.xmlhttp.send(this.URLString);
    			}
    		}
    	};
    
    	this.reset();
    	this.createAJAX();
    }
    Thank you in advance,
    Rach
  • Logician
    New Member
    • Feb 2007
    • 210

    #2
    Originally posted by bonneylake
    Code:
    <SELECT NAME="options" id="options"
    onChange="this.form.custnum.value=this.options[this.selectedIndex].value;javascript:initFormEvents();">
    You can't name a <select> 'options' since it has such a property already and it's causing an addressing error.

    Comment

    • bonneylake
      Contributor
      • Aug 2008
      • 769

      #3
      Hey Logician,

      Well i tried that but i am still getting the same error. an i had to make some changes because i realized after i tried to do what you told me that my form was not even auto populating. An i also realized i am getting the same error when i try to create a new customer number an also when i autopopulate the form which makes me wonder if maybe the problem is with onchange? but here is the parts i changed everything else is the same.

      javascript on form page
      Code:
      var ajax = new sack();
      	var currentClientID=false;
      	function getClientData()
      	{
      		var clientId = document.getElementById('clientID').value;
      			currentClientID = clientId
      			ajax.requestFile = 'getClient.cfm?custnum='+clientId;	// Specifying which file to get
      			ajax.onCompletion = showClientData;	// Specify function that will be executed after file has been found
      			ajax.runAJAX();		// Execute AJAX function			
      		
      	}
      	
      	function showClientData()
      	{
      		var formObj = document.forms['page1'];	
      		eval(ajax.response);
      	}
      	
      	
      	function initFormEvents()
      	{
      		document.getElementById('clientID').onblur = getClientData;
      		document.getElementById('clientID').focus();
      		document.getElementById("options").onchange = getClientData;
      	}
      	
      	
      	window.onload = initFormEvents;
      html part
      Code:
      Customer Number*:<input type="text" name="custnum" id="clientID" value=""  ONKEYUP="autoComplete(this,this.form.options,'value',false)"  onChange="validate(this.form.custnum,'Customer Number')"/>
      <SELECT NAME="customer" id="options"
      onChange="this.form.custnum.value=this.options[this.selectedIndex].value;javascript:initFormEvents();">
      <cfoutput query="getcustnum">
      <option value="#fk_custNum#">#fk_custNum#</option>
      </cfoutput>
      </SELECT>
      Thank you for all the help :),
      Rach

      Comment

      • acoder
        Recognized Expert MVP
        • Nov 2006
        • 16032

        #4
        The reason the auto-complete isn't working is that you forgot to change this line
        Code:
        autoComplete(this,this.form.options,'value',false)
        to refer to the new name:
        [code=javascript]autoComplete(th is,this.form.cu stomer,'value', false)[/code]

        Comment

        • bonneylake
          Contributor
          • Aug 2008
          • 769

          #5
          Hey Acoder,

          the autocomplete is working. but i am still getting the error of object expected.

          here is what i changed

          Code:
          Customer Number*:<input type="text" name="custnum" id="clientID" value=""  ONKEYUP="autoComplete(this,this.form.customer,'value',false)"  onChange="validate(this.form.custnum,'Customer Number')"/>
          <SELECT NAME="customer" id="options"
          onChange="this.form.custnum.value=this.options[this.selectedIndex].value;javascript:initFormEvents();">
          <cfoutput query="getcustnum">
          <option value="#fk_custNum#">#fk_custNum#</option>
          </cfoutput>
          </SELECT>
          any suggestions, Thank you :),
          Rach

          Comment

          • acoder
            Recognized Expert MVP
            • Nov 2006
            • 16032

            #6
            What line does the error occur on? Check the error console in a decent browser such as Firefox - it'll give you more information about the error, if indeed it occurs in that browser.

            Comment

            • bonneylake
              Contributor
              • Aug 2008
              • 769

              #7
              Hey Acoder,

              when i tried it out in firefox it says validate is not defined.also, when i try to type in a different customer number an go to another field it gets rid of what i typed in customer number in firefox, but it doesn't do this in internet explorer just gives me an error.

              Thank you,
              Rach

              Comment

              • acoder
                Recognized Expert MVP
                • Nov 2006
                • 16032

                #8
                Well, that's a lot more useful. Have you actually defined validate() anywhere?

                Comment

                • bonneylake
                  Contributor
                  • Aug 2008
                  • 769

                  #9
                  Hey Acoder,

                  as far as i know, no. I looked through all the files i have for the word validate. An only place that has validate is here

                  Code:
                  Customer Number*:<input type="text" name="custnum" id="clientID" value=""  ONKEYUP="autoComplete(this,this.form.customer,'value',false)"  onChange="validate(this.form.custnum,'Customer Number')"/>
                  i took validate out an i don't get the error anymore when i autopopulate or type something different into the customer number, so can i leave the validate part out of it? heres it updated without validate

                  Code:
                  Customer Number*:<input type="text" name="custnum" id="clientID" value=""  ONKEYUP="autoComplete(this,this.form.customer,'value',false)"  onChange="this.form.custnum,'Customer Number'"/>
                  However, i am still having trouble with it. when i type something into customer number an it doesn't exist in the drop down an i go to click into another field it completely gets ride of what i typed in the customer number field. Any suggestions on how to fix that?

                  Thank you :),
                  Rach

                  Comment

                  • acoder
                    Recognized Expert MVP
                    • Nov 2006
                    • 16032

                    #10
                    Get rid of the onchange completely. You must have copied the code from somewhere that used a validate() function onchange.

                    Comment

                    • bonneylake
                      Contributor
                      • Aug 2008
                      • 769

                      #11
                      Hey Acoder,

                      The only thing wrong with taking out onchange is that then it doesn't populate the drop down box right. Like lets say i have 2 customer number values one called 4 and one called 444. If i just type 4 its putting 444 an when i go and take out the extra 2 4's its not changing the drop down box to 4 and instead its leaving it as 444 even though i typed in just 4(i hope that makes since) .

                      an the way i am trying to get it to work is if i start typing in customer number , as i am typeing in the customer number it populates the drop down box an then when you choose the value in the drop down box it populates the form.

                      but can i leave onchange in there or is that going to continue to cause trouble?

                      Thank you,
                      Rach

                      Comment

                      • acoder
                        Recognized Expert MVP
                        • Nov 2006
                        • 16032

                        #12
                        Does the following not work?
                        [code=html]Customer Number*:<input type="text" name="custnum" id="clientID" value="" ONKEYUP="autoCo mplete(this,thi s.form.customer ,'value',false )"/>[/code]

                        Comment

                        • bonneylake
                          Contributor
                          • Aug 2008
                          • 769

                          #13
                          Acoder,

                          it does, but then it doesn't work. ok heres an example. lets say i type 1. 1 is the name of the customer number i want. But its trying to guess the number so behind the 1 in my input field it adds 024 (which is another field called 1024), an would like to get it to stop guessing the number for me in my input field as well if thats possible. but anyway it puts 1024 also in my dropdown box. well when i remove the rest of the 1024 and put 1 it doesn't update the dropdown box from 1024 to 1 and instead remains 1024. however, it does populate the rest of the form with the correct information. Just need the drop down box to work correctly. Hope this makes since.

                          Thank you,
                          Rach

                          Comment

                          • acoder
                            Recognized Expert MVP
                            • Nov 2006
                            • 16032

                            #14
                            I tested with this simple example and it works fine:
                            [code=html]<form>
                            Customer Number*:<input type="text" name="custnum" id="clientID" value="" ONKEYUP="autoCo mplete(this,thi s.form.customer ,'value',false) ">
                            <SELECT NAME="customer" id="options"
                            onChange="this. form.custnum.va lue=this.option s[this.selectedIn dex].value;">
                            <option value="1">1</option>
                            <option value="1024">10 24</option>
                            </SELECT>
                            </form>[/code]

                            Comment

                            • bonneylake
                              Contributor
                              • Aug 2008
                              • 769

                              #15
                              Hey Acoder,

                              yep you are right your example works like it needs to. Typed yours in an it worked. But what i have is not working at all an makes no since to me! When i start typing in something it keeps auto filling the input field with a value thats in the dropdown box.like if i type 1 it puts 024 in blue right behind it in the input field and makes the drop down box 1024. It doesn't even seem to recognize 1 because when i type 1, 1 doesn't come up only the 1024 number. But when i click off of it, it auto fills the form with the values from customer number 1 it just doesn't change the drop down box from 1024 to 1.

                              but heres the form again
                              Code:
                              Customer Number*:<input type="text" name="custnum" id="clientID" value=""  ONKEYUP="autoComplete(this,this.form.customer,'value',false)"  <!---onChange="this.form.custnum,'Customer Number'"--->/>
                              <SELECT NAME="customer" id="options"
                              onChange="this.form.custnum.value=this.options[this.selectedIndex].value;<!---javascript:initFormEvents();--->">
                              <cfoutput query="getcustnum">
                              <option value="#fk_custNum#">#fk_custNum#</option>
                              </cfoutput>
                              </SELECT>
                              an here is the javascript on the form page.
                              Code:
                              <script type="text/javascript">
                              
                              var ajax = new sack();
                              	var currentClientID=false;
                              	function getClientData()
                              	{
                              		var clientId = document.getElementById('clientID').value;
                              			currentClientID = clientId
                              			ajax.requestFile = 'getClient.cfm?custnum='+clientId;	// Specifying which file to get
                              			ajax.onCompletion = showClientData;	// Specify function that will be executed after file has been found
                              			ajax.runAJAX();		// Execute AJAX function			
                              		
                              	}
                              	
                              	function showClientData()
                              	{
                              		var formObj = document.forms['page1'];	
                              		eval(ajax.response);
                              	}
                              	
                              	
                              	function initFormEvents()
                              	{
                              		document.getElementById('clientID').onblur = getClientData;
                              		document.getElementById('clientID').focus();
                              		document.getElementById("options").onchange = getClientData;
                              	}
                              	
                              	
                              	window.onload = initFormEvents;
                              	</script>
                              Thank you for all the help,
                              Rach

                              Comment

                              Working...