Results 1 to 9 of 9

Thread: Auto Save Form script - supported field types

  1. #1
    Join Date
    Nov 2014
    Posts
    5
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Question Auto Save Form script - supported field types

    1) Script Title: Auto Save Form script

    2) Script URL (on DD): http://www.dynamicdrive.com/dynamici...tosaveform.htm

    3) Describe problem: The Script don't support the field type 'number'.

    Hello,

    i love this script. It's really easy to use and works fine! First thank you for that! I'm a beginner in coding and would like to use these script for for fields witch the type="number". Nows somebody an easy way to modify the script so that it is usable for numberfields?

    Thank you!!!
    Jonas

    Ps: Sorry for my bad english!

  2. #2
    Join Date
    Dec 2008
    Location
    Portsmouth, UK
    Posts
    1,891
    Thanks
    2
    Thanked 441 Times in 435 Posts

    Default

    changes in red

    Code:
    /*
    * Auto Save Form script
    * Created: Aug 8th, 2011 by DynamicDrive.com. This notice must stay intact for usage
    * Author: Dynamic Drive at http://www.dynamicdrive.com/
    * Visit http://www.dynamicdrive.com/ for full source code
    */
    
    function autosaveform(setting){
    	if (!autosaveform.domstorage || !window.JSON) //if browser doesn't support dom storage or JSON
    		return
    	var $=jQuery
    	var defaults={ //default setting values
    		includefields:['text', 'textarea', 'checkbox', 'radio', 'select'],
    		savingmsg:'Auto Saving form values...',
    		pause:1000,
    		onsave:function(f){}
    	}
    	var setting=$.extend({}, defaults, setting)
    	this.setting=setting
    	this.onsave=setting.onsave
    	var fieldskeywords=setting.includefields.join(" ")
    	setting.includefields=$.map(setting.includefields, function(a){ //mold fieldskeywords into array of jQuery selector strings
    		return (a=="select" || a=="textarea")? a : "input[type='"+a+"']"
    	})
    	var thissession=this
    	jQuery(function($){ //on document.ready
    		var $f=$('form#'+setting.formid).css({position:'relative'})
    		thissession.f=$f.get(0)
    		var targetfields=$(thissession.f.elements).filter(setting.includefields.join(',')).get() //filter out form fields that should be auto saved
    		thissession.targetfields=targetfields
    		thissession.loadfields() //load saved value into these fields (if any)
    		var formevts='keydown cut paste'+ (/(checkbox)|(radio)|(select)/i.test(fieldskeywords)? ' change' : '') //Event keywords for form that will trigger saving of form field values
    		$f.bind(formevts, function(e){
    			var target=e.target.type.replace(/-\w+/i, "") || e.target.tagName //get target user is currently interacting with (using keywords found in fieldskeywords)
    			if (fieldskeywords.indexOf(target.toLowerCase())!=-1)
    				thissession.activatesave()
    		})
    		$f.submit(function(){
    			thissession.savefields("clear") //clear saved form values when form is submitted
    		})
    		if (setting.savingmsg)
    			thissession.$statusdiv=$('<div class="savestatus" style="visibility:hidden">' + setting.savingmsg + '</div>').prependTo($f)
    	})
    }
    
    autosaveform.prototype={
    
    	getel:function(id){
    		return (document.getElementById(id) || this.f.elements[id])
    	},
    
    	getelname:function(el){
    		return el.id || el.name
    	},
    
    	activatesave:function(){
    		var thissession=this
    		clearTimeout(this.savetimer)
    		this.savetimer=setTimeout(function(){thissession.savefields()}, this.setting.pause)
    	},
    
    	savefields:function(action){
    		var savedvalue={}
    		var processedboxes=[]
    		if (action!="clear"){
    			for (var i=0, targets=this.targetfields, len=targets.length; i<len; i++){ //loop thru all fields in form that script should check whether to save their value
    				var elname=this.getelname(targets[i])
    				if (elname){ //if element carries an ID or NAME attribute
    					if ((/text/i.test(targets[i].type)||/number/i.test(targets[i].type)) && targets[i].value!=""){ //for textarea and input type=text elements
    							savedvalue[elname]=targets[i].value
    					}
    					else if (/(checkbox)|(radio)/i.test(targets[i].type)){ //for checkbox/radios
    						if (jQuery.inArray(elname, processedboxes)==-1){ //if this group of checkboxes (ones sharing the same name) haven't been processed yet
    							for (var c=0, cgroup=this.f.elements[elname], clength=cgroup.length; c<clength; c++){ //loop through checkboxes/ radio buttons within group
    								if (cgroup[c].checked){
    									savedvalue[elname]=(typeof savedvalue[elname]=="undefined")? [c] : savedvalue[elname].concat([c])
    								}
    							} //end for loop
    							processedboxes.push(targets[i].name)
    						}
    					}
    					else if (targets[i].type.indexOf("select")!=-1){ //for select menus
    						for (var o=0, opts=targets[i].options, olength=opts.length; o<olength; o++){
    							if (opts[o].selected)
    								savedvalue[elname]=(typeof savedvalue[elname]=="undefined")? [o] : savedvalue[elname].concat([o])
    						}
    					}
    				} //end if elname
    			} //end for loop
    			if (this.$statusdiv)
    				this.$statusdiv.css({opacity:0, visibility:'visible'}) //show "saving form" notice temporarily
    					.animate({opacity:1},200).delay(400).animate({opacity:0},200)
    			try{ //call onsave event handler
    				this.onsave(this.f, savedvalue)
    			}
    			catch(e){
    				throw new Error("An error has occured inside your onsave() function:\n" + e.message)
    			}
    		} //end if action
    		autosaveform._storage(this.f, "save", JSON.stringify(savedvalue))
    	},
    
    	loadfields:function(){
    		try{
    			var loadedvalue=JSON.parse(autosaveform._storage(this.f, "load"))
    		}catch(e){
    			var loadedvalue={}
    		}
    		for (var elname in loadedvalue){ //loop thru each field name property inside loadedvalue
    			if (loadedvalue.hasOwnProperty(elname)){
    				var el=this.getel(elname)
    				if (el){ //if element with this name/id actually exists on the form (form may have been changed)
    					if ((/text/i.test(targets[i].type)||/number/i.test(targets[i].type)) && typeof loadedvalue[elname]=="string"){ //if this is a input type="text" or textarea element
    						el.value=loadedvalue[elname]
    					}
    					else if (typeof loadedvalue[elname]=="object" && el.type==undefined && /(checkbox)|(radio)/i.test(el[0].type)){ //checkbox/radios
    						for (var c=0, cgroup=this.f.elements[elname], clength=loadedvalue[elname].length; c<clength; c++){ //loop through saved checkboxes/ radio buttons array of numbers
    							var checkedindex=loadedvalue[elname][c]
    							if (cgroup[checkedindex]){ //if checkbox/radio button at this index exists on the page
    								cgroup[checkedindex].checked=true
    							}
    						} //end for loop
    					}
    					else if (/select/i.test(el.type)){ //select menu
    						for (var o=0, opts=el.options, olength=loadedvalue[elname].length; o<olength; o++){ //loop through saved select array of numbers
    							var selectedindex=loadedvalue[elname][o]
    							opts[selectedindex].selected=true
    						}
    					}
    				}
    			} //end if
    		} //end for
    	}
    
    }
    
    
    autosaveform.domstorage=window.localStorage || (window.globalStorage? globalStorage[location.hostname] : null)
    //Create cookie prefix using the page's URL. Mold from "http://mysite.com/sub/file.htm" for example to "sub/file.htm"
    autosaveform.cookieprefix=location.href.replace(new RegExp("("+location.host+"/)|("+location.protocol+"//)", "g"), "")
    
    autosaveform._storage=function(form, action, data){
    	var domstorage=autosaveform.domstorage
    	if (action=="load"){
    		return domstorage[this.cookieprefix+"_"+form.id]
    	}
    	else if (action=="save"){
    		domstorage[this.cookieprefix+"_"+form.id]=data
    	}
    }
    Vic
    God Loves You and will never love you less.
    http://www.vicsjavascripts.org/Home.htm
    If my post has been useful please donate to http://www.operationsmile.org.uk/

  3. #3
    Join Date
    Nov 2014
    Posts
    5
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default

    Hello,

    thank you very much for your fast answer! I modify my code, but unfortunately your solution don't work for me, or is there a fault in my corrected code?

    Code:
    [...]
    
    <script src="js/jQuery-autosave/autosaveform.js"></script>
    <script>
    	var formsave1=new autosaveform({
    		formid: 'tippform',
    		savingmsg: "", //disables "auto saving" message from appearing
    		pause: 1000 //<--no comma following last option!
    	})
    </script>
    
    [...]
    
    echo "<form action='main_seasons_admin_panel.php' method='POST' id='tippform'>";
    	echo "<input type='number' min='0' max='99' class='tipp' name='ti_h_t'>";
    	echo "<input type='number' min='0' max='99' class='tipp tippr' name='ti_g_t'>";
    echo "</form>";
    
    [...]
    js-code:

    Code:
    /*
    * Auto Save Form script
    * Created: Aug 8th, 2011 by DynamicDrive.com. This notice must stay intact for usage 
    * Author: Dynamic Drive at http://www.dynamicdrive.com/
    * Visit http://www.dynamicdrive.com/ for full source code
    */
    
    function autosaveform(setting){
    	if (!autosaveform.domstorage || !window.JSON) //if browser doesn't support dom storage or JSON
    		return
    	var $=jQuery
    	var defaults={ //default setting values
    		includefields:['text', 'textarea', 'checkbox', 'radio', 'select'],
    		savingmsg:'Auto Saving form values...',
    		pause:1000,
    		onsave:function(f){}
    	}
    	var setting=$.extend({}, defaults, setting)
    	this.setting=setting
    	this.onsave=setting.onsave
    	var fieldskeywords=setting.includefields.join(" ")
    	setting.includefields=$.map(setting.includefields, function(a){ //mold fieldskeywords into array of jQuery selector strings
    		return (a=="select" || a=="textarea")? a : "input[type='"+a+"']"
    	})
    	var thissession=this
    	jQuery(function($){ //on document.ready
    		var $f=$('form#'+setting.formid).css({position:'relative'})
    		thissession.f=$f.get(0)
    		var targetfields=$(thissession.f.elements).filter(setting.includefields.join(',')).get() //filter out form fields that should be auto saved
    		thissession.targetfields=targetfields
    		thissession.loadfields() //load saved value into these fields (if any)
    		var formevts='keydown cut paste'+ (/(checkbox)|(radio)|(select)/i.test(fieldskeywords)? ' change' : '') //Event keywords for form that will trigger saving of form field values
    		$f.bind(formevts, function(e){
    			var target=e.target.type.replace(/-\w+/i, "") || e.target.tagName //get target user is currently interacting with (using keywords found in fieldskeywords)
    			if (fieldskeywords.indexOf(target.toLowerCase())!=-1)
    				thissession.activatesave()
    		})
    		$f.submit(function(){
    			thissession.savefields("clear") //clear saved form values when form is submitted
    		})
    		if (setting.savingmsg)
    			thissession.$statusdiv=$('<div class="savestatus" style="visibility:hidden">' + setting.savingmsg + '</div>').prependTo($f)
    	})
    }
    
    autosaveform.prototype={
    
    	getel:function(id){
    		return (document.getElementById(id) || this.f.elements[id])
    	},
    
    	getelname:function(el){
    		return el.id || el.name
    	},
    
    	activatesave:function(){
    		var thissession=this
    		clearTimeout(this.savetimer)
    		this.savetimer=setTimeout(function(){thissession.savefields()}, this.setting.pause)
    	},
    
    	savefields:function(action){ 
    		var savedvalue={}
    		var processedboxes=[]
    		if (action!="clear"){
    			for (var i=0, targets=this.targetfields, len=targets.length; i<len; i++){ //loop thru all fields in form that script should check whether to save their value
    				var elname=this.getelname(targets[i])
    				if (elname){ //if element carries an ID or NAME attribute
    					if ((/text/i.test(targets[i].type)||/number/i.test(targets[i].type)) && targets[i].value!=""){ //for textarea and input type=text elements
    							savedvalue[elname]=targets[i].value
    					}
    					else if (/(checkbox)|(radio)/i.test(targets[i].type)){ //for checkbox/radios
    						if (jQuery.inArray(elname, processedboxes)==-1){ //if this group of checkboxes (ones sharing the same name) haven't been processed yet
    							for (var c=0, cgroup=this.f.elements[elname], clength=cgroup.length; c<clength; c++){ //loop through checkboxes/ radio buttons within group
    								if (cgroup[c].checked){
    									savedvalue[elname]=(typeof savedvalue[elname]=="undefined")? [c] : savedvalue[elname].concat([c])
    								}
    							} //end for loop
    							processedboxes.push(targets[i].name)
    						}
    					}
    					else if (targets[i].type.indexOf("select")!=-1){ //for select menus
    						for (var o=0, opts=targets[i].options, olength=opts.length; o<olength; o++){
    							if (opts[o].selected)
    								savedvalue[elname]=(typeof savedvalue[elname]=="undefined")? [o] : savedvalue[elname].concat([o])
    						}
    					}
    				} //end if elname
    			} //end for loop
    			if (this.$statusdiv)
    				this.$statusdiv.css({opacity:0, visibility:'visible'}) //show "saving form" notice temporarily
    					.animate({opacity:1},200).delay(400).animate({opacity:0},200)
    			try{ //call onsave event handler
    				this.onsave(this.f, savedvalue)
    			}
    			catch(e){
    				throw new Error("An error has occured inside your onsave() function:\n" + e.message)
    			}
    		} //end if action
    		autosaveform._storage(this.f, "save", JSON.stringify(savedvalue))
    	},
    
    	loadfields:function(){
    		try{
    			var loadedvalue=JSON.parse(autosaveform._storage(this.f, "load"))
    		}catch(e){
    			var loadedvalue={}
    		}
    		for (var elname in loadedvalue){ //loop thru each field name property inside loadedvalue
    			if (loadedvalue.hasOwnProperty(elname)){
    				var el=this.getel(elname)
    				if (el){ //if element with this name/id actually exists on the form (form may have been changed)
    					if ((/text/i.test(targets[i].type)||/number/i.test(targets[i].type)) && typeof loadedvalue[elname]=="string"){ //if this is a input type="text" or textarea element
    						el.value=loadedvalue[elname]
    					}
    					else if (typeof loadedvalue[elname]=="object" && el.type==undefined && /(checkbox)|(radio)/i.test(el[0].type)){ //checkbox/radios
    						for (var c=0, cgroup=this.f.elements[elname], clength=loadedvalue[elname].length; c<clength; c++){ //loop through saved checkboxes/ radio buttons array of numbers
    							var checkedindex=loadedvalue[elname][c]
    							if (cgroup[checkedindex]){ //if checkbox/radio button at this index exists on the page
    								cgroup[checkedindex].checked=true
    							}
    						} //end for loop				
    					}
    					else if (/select/i.test(el.type)){ //select menu
    						for (var o=0, opts=el.options, olength=loadedvalue[elname].length; o<olength; o++){ //loop through saved select array of numbers
    							var selectedindex=loadedvalue[elname][o]
    							opts[selectedindex].selected=true
    						}
    					}
    				}
    			} //end if
    		} //end for
    	}
    
    }
    
    
    autosaveform.domstorage=window.localStorage || (window.globalStorage? globalStorage[location.hostname] : null)
    //Create cookie prefix using the page's URL. Mold from "http://mysite.com/sub/file.htm" for example to "sub/file.htm"
    autosaveform.cookieprefix=location.href.replace(new RegExp("("+location.host+"/)|("+location.protocol+"//)", "g"), "")
    
    autosaveform._storage=function(form, action, data){
    	var domstorage=autosaveform.domstorage
    	if (action=="load"){
    		return domstorage[this.cookieprefix+"_"+form.id]
    	}
    	else if (action=="save"){
    		domstorage[this.cookieprefix+"_"+form.id]=data
    	}
    }
    Jonas

  4. #4
    Join Date
    Dec 2008
    Location
    Portsmouth, UK
    Posts
    1,891
    Thanks
    2
    Thanked 441 Times in 435 Posts

    Default

    you are right

    I have tried to fix it but am unsuccessful

    I will try further and let you know if successful
    Vic
    God Loves You and will never love you less.
    http://www.vicsjavascripts.org/Home.htm
    If my post has been useful please donate to http://www.operationsmile.org.uk/

  5. The Following User Says Thank You to vwphillips For This Useful Post:

    hallojs (11-22-2014)

  6. #5
    Join Date
    Nov 2014
    Posts
    5
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default

    Hey,

    thank you again! I'm so grateful for you help! It would be realy cool to have a solution for this problem.

    Jonas

  7. #6
    Join Date
    Dec 2008
    Location
    Portsmouth, UK
    Posts
    1,891
    Thanks
    2
    Thanked 441 Times in 435 Posts

    Default

    this verson uses a cookie and saves every X seconds
    + form fields must have names

    Code:
    <!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" xml:lang="en" lang="en">
    
    <head>
      <title></title>
    <style>
    
    #savestatus{ /* Style for the "Saving Form Contents" DIV that is shown at the top of the form */
    width:200px;
    padding:2px 5px;
    border:1px solid gray;
    background:#fff6e5;
    -webkit-box-shadow: 0 0 8px #818181;
    box-shadow: 0 0 8px #818181;
    -moz-border-radius: 5px;
    -webkit-border-radius: 5px;
    border-radius:5px;
    color:red;
    position:absolute;
    top:-10px;
    }
    
    form#feedbackform div{ /*CSS used by demo form*/
    margin-bottom:9px;
    }
    
    </style>
    
    <script type="text/javascript" >
    
    
    var autosaveform={
    
     Init:function(o){
      var id=o.formid,frm=document.getElementById(id),s=document.getElementById(o.savestatusid),hd=o.hidedelay,sd=o.savedelay,cd=o.cookiedays;
      if (frm){
       var els=frm.elements,a='',c,z0=0,z1=0,z1a;
       o.f=[];
       for (;z0<els.length;z0++){
        if (els[z0].name&&a.indexOf(els[z0].name+',')==-1){
         a+=els[z0].name+','
         o.f.push([els[z0].name,els[z0].type.toLowerCase()]);
        }
       }
      }
      for (;z1<o.f.length;z1++){
       c=this.cookie(id+o.f[z1][0]);
       if (c){
        if (o.f[z1][1].match('select')){
         frm[o.f[z1][0]].selectedIndex=c;
        }
        else if (o.f[z1][1].match('radio')||o.f[z1][1].match('checkbox')){
         c=c.split(',');
         for (var z1a=0;z1a<c.length-1;z1a++){
          frm[o.f[z1][0]][z1a].checked=c[z1a]=='true';
         }
        }
        else {
         frm[o.f[z1][0]].value=c;
        }
       }
      }
      o.id=id;
      o.frm=frm;
      o.days=typeof(cd)=='number'&&cd>0?cd:-1;
      o.s=s;
      o.hd=typeof(hd)=='number'&&hd>0?hd:1000;
      setInterval(function(){ autosaveform.save(o); },typeof(sd)=='number'&&sd>0?sd:5000);
      autosaveform.save(o);
     },
    
     save:function(o){
      for (var z0=0,c,z0a;z0<o.f.length;z0++){
       if (o.f[z0][1].match('select')){
        this.setcookie(o,o.id+o.f[z0][0],o.frm[o.f[z0][0]].selectedIndex);
       }
       else if (o.f[z0][1].match('radio')||o.f[z0][1].match('checkbox')){
        for (var c='',z0a=0;z0a<o.frm[o.f[z0][0]].length;z0a++){
         c+=o.frm[o.f[z0][0]][z0a].checked+',';
        }
        this.setcookie(o,o.id+o.f[z0][0],c);
       }
       else {
        this.setcookie(o,o.id+o.f[z0][0],o.frm[o.f[z0][0]].value);
       }
      }
      if (o.s){
       o.s.style.visibility='visible';
       o.to=setTimeout(function(){ o.s.style.visibility='hidden'; },o.hd);
      }
     },
    
     cookie:function(nme){
      var re=new RegExp(nme+'=[^;]+','i');
      return document.cookie.match(re)?document.cookie.match(re)[0].split("=")[1]:null;
     },
    
     setcookie:function(o,n,v){
      o.days!=-1?document.cookie=n+'='+v+(typeof(o.days)=='number'?';expires='+(new Date(new Date().getTime()+o.days*86400000).toGMTString())+';path/;':';'):null;
     }
    
    
    }
    
    </script>
    
    </head>
    
    <body>
    <div id="savestatus" >Saved</div>
    <form id="feedbackform" method="post">
    
    <div>Name:<br /> <input name="username" type="text" size="35" /></div>
    <div>Number:<br /> <input name="number" type="number" size="35" /></div>
    
    <div>Sex: <input type="radio" name="sex" value="male" />Male <input type="radio" name="sex" value="female" />Female</div>
    
    <div>Hobbies: <input type="checkbox" name="hobby" />Reading <input type="checkbox" name="hobby" />Sports <input type="checkbox" name="hobby" />Movies</div>
    
    <div>Country: <select id="country" name="country">
    	<option>USA</option>
    	<option>Canada</option>
    	<option>Other</option>
    	</select>
    </div>
    
    <div>State/Province:<br /> <input name="state" type="text" size="20" /></div>
    
    <div>About Yourself:<br /> <textarea name="feedback" style="width:350px;height:150px"></textarea></div>
    
    <input type="submit" />
    
    </form>
    <script>
    
    autosaveform.Init({
    	formid:'feedbackform',
        savedelay:5000,
        cookiedays:10,
        savestatusid:'savestatus',
    	hidedelay:1000 //<--no comma following last option!
    })
    
    </script>
    
    </body>
    
    </html>
    Vic
    God Loves You and will never love you less.
    http://www.vicsjavascripts.org/Home.htm
    If my post has been useful please donate to http://www.operationsmile.org.uk/

  8. The Following User Says Thank You to vwphillips For This Useful Post:

    hallojs (11-24-2014)

  9. #7
    Join Date
    Nov 2014
    Posts
    5
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default

    Hello,

    now it works! Thank you very much! Dynamik Drive and this forum are so helpful! It's realy cool.

    Jonas

  10. #8
    Join Date
    Nov 2014
    Posts
    5
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default

    Hello,

    sorry for asking again, but after testing the script a little bit I found out that the script only work after one refresh of the page. I think after one refresh changes not be saved again. Is it right? Is there a solution for this problem? Thank you very much!

    Jonas

  11. #9
    Join Date
    Dec 2008
    Location
    Portsmouth, UK
    Posts
    1,891
    Thanks
    2
    Thanked 441 Times in 435 Posts

    Default

    sorry I missed your last post

    I have tested the script using Moz FF with a number of reloads and refreashes and it works for me

    note that it uses cookies and cookies must be enabled on your machine
    Vic
    God Loves You and will never love you less.
    http://www.vicsjavascripts.org/Home.htm
    If my post has been useful please donate to http://www.operationsmile.org.uk/

Similar Threads

  1. Auto Save Form script- Radio button not saved
    By dtolj in forum Dynamic Drive scripts help
    Replies: 1
    Last Post: 04-23-2014, 08:56 PM
  2. Auto Save Form Values issue / enchancement
    By billbrach in forum Dynamic Drive scripts help
    Replies: 4
    Last Post: 08-02-2012, 04:16 PM
  3. Auto Save Form Processing Previous Form Submission
    By Meleo in forum Dynamic Drive scripts help
    Replies: 3
    Last Post: 07-09-2012, 04:38 AM
  4. Send auto reply to form field email address
    By stealthmode666 in forum PHP
    Replies: 5
    Last Post: 12-12-2008, 06:14 AM
  5. Auto expanding form field based on content
    By izzysanime in forum HTML
    Replies: 0
    Last Post: 09-04-2008, 11:52 PM

Bookmarks

Posting Permissions

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