Solved

How do I keep entered form data in form with JS when follow error link and return?

Posted on 2014-07-23
15
585 Views
Last Modified: 2014-08-01
I am attempting to persist entered information in a form after the user clicks submit and the error page returns him/her back to the form page. Attached is the code for the form and the persistence.js

<form name="contactForm" method="post" id="contactForm" 
action="http://www.thumbsupproduction.com/inc/mail/fmj.php" onsubmit="return verifyMe()">
        <input type="hidden" name="subject" value="Contact Form" />
        <input type="hidden" name="recipients" value="form" />
        <input type="hidden" name="derive_fields" value="IP = REMOTE_ADDR, Browser = 

HTTP_USER_AGENT, 
Referrer = HTTP_REFERER" />
        <input type="hidden" name="mail_options" 
value="HTMLTemplate=mail.contact.htm,TemplateMissing=N/A,KeepLines" />
        <div align="center"> <font color="#000000"  size="3em" face="Open Sans, sans-serif"><strong>Contact Form</strong></font> <br />
          <br />
        </div>
        <div align="left"><font face="Open Sans, sans-serif" size="2em"><strong><font 

color="#ff0000">*</font><font color="#000000"><em> Name</em>
          <input type="text"  name="realname" id="realname" maxlength="20" size="20" 
			onfocus="this.className='currentField'" 
			onchange="this.className='changedField'" />&nbsp;&nbsp;<font color="#FF0000">*</font><em>Email</em>
          <input type="text" name="email" id="emailaddy" maxlength="40" size="20" 
			onfocus="this.className='currentField'" 
			onchange="this.className='changedField'" />
         <br /><center>
          <font color="#ff0000"><em>* Required Fields</em></font></font></strong></font></center> 

</div>
        <p align="left"><font color="#000000"  size="2em" face="Open Sans, sans-serif"><strong>I am 

interested in 
          the following (check all that apply):</strong><br />
          <input name="info[]" type="checkbox" value="dvd" 
				onfocus="this.className='currentField'" 
				onchange="this.className='changedField'" />
          DVD Production (Please describe in Comment section below)<br />
          <input name="info[]" type="checkbox" value="BunnyDVD" 
				onfocus="this.className='currentField'" 
				onchange="this.className='changedField'" />
          DVD of Against all Odds<br />
          <br />
          Mailing Address :
          <input type="text" name="Address" maxlength="30" size="30" 
				onfocus="this.className='currentField'" 
				onchange="this.className='changedField'" />
          <br />
          <br />
          City:
          <input type="text" name="City" maxlength="30" size="30" 
				onfocus="this.className='currentField'" 
				onchange="this.className='changedField'" />
         &nbsp;&nbsp;&nbsp
          State:
          <input type="text" name="State" maxlength="4" size="4" 
				onfocus="this.className='currentField'" 
				onchange="this.className='changedField'" />
          &nbsp;&nbsp;&nbspZip Code:
          <input type="text" name="ZipCode" size="8" maxlength="8" 
				onfocus="this.className='currentField'" 
				onchange="this.className='changedField'" />
          <br />
          <br />
          Day Phone # (xxx-xxx-xxxx):
          <input type="text" name="dayphone" id="dayphone" size="14" maxlength="14" 

				onfocus="this.className='currentField'" 

				onchange="this.className='changedField'" />
          &nbsp;&nbsp;&nbsp;&nbsp; 
          Evening Phone # (xxx-xxx-xxxx):
          <input type="text" name="evephone" id="evephone" size="14" maxlength="14" 
				onfocus="this.className='currentField'" 
				onchange="this.className='changedField'" />
          <br />
          <br />
          Website Address:
          <input type="text" name="Website" size="14" maxlength="50" 

				onfocus="this.className='currentField'" 

				onchange="this.className='changedField'" />
          <br />
          </font><font color="#000000"  size="2em" face="Trebuchet MS, Arial, sans-serif"><br />
          <strong>Please let us know how you happened to visit us</strong>:<br />
          <input name="referred[]" type="checkbox" 
				value="Google" 
				onfocus="this.className='currentField'" 
				onchange="this.className='changedField'" />
          Google<br />
          <input name="referred[]"  type="checkbox" 
				value="youtube" 
				onfocus="this.className='currentField'" 
				onchange="this.className='changedField'" />
          YouTube<br />
          <input name="referred[]" type="checkbox"  
				value="LinkedIn" 
				onfocus="this.className='currentField'" 
				onchange="this.className='changedField'" />
          LinkedIn<br />
          <input name="referred[]"  type="checkbox"  
				value="bing" 
				onfocus="this.className='currentField'" 
				onchange="this.className='changedField'" />
          Bing<br />
          <input name="referred[]" type="checkbox" 
				value="Other Search Engine" 
				onfocus="this.className='currentField'" 
				onchange="this.className='changedField'" />
          Other Search Engine (please list in comment section)<br />
          <input name="referred[]"  type="checkbox"  
				value="other" 
				onfocus="this.className='currentField'" 
				onchange="this.className='changedField'" />
          Other (Please list in Comment section)<br />
          </font></p>
        <p align="center"><strong> <font color="#000000" size="3em">Comments / 

Feedback</font></strong><br />
          <textarea cols="48" name="Notes" rows="10" ></textarea>
        </p>
        <p align="left"><font color="#000000" face="Open Sans,sans-serif" size="2em"><strong> <font 

color="#ff0000"> *</font>Enter the code word: <font 

color="#ff0000"><em>smile</em></font></strong></font>
          <input type="text" name="verCode" id="verCode" size="32" maxlength="16" value="" />
        </p>
        <p>&nbsp;</p>
        <p align="center" ><font color="#000000"  face="Open Sans, sans-serif" size="3em"><strong> 

Please click the Submit button once to send form.</strong></font><br />
          <input type="submit" name="contact" value="Submit" />
          <input type="reset"  onclick="resetForm('contactForm')" value="Reset Form" />
          <br />
        </p>
      </form>

Open in new window


(the id tag is for my validate.js code) 

I embedded into head:
<code>
 <script type="text/javascript" src="jquery-1.11.1.min.js"></script>
 <script type="text/javascript" src="jquery.cookie.js"></script>
<script type="text/javascript" src="persistence.js"></script>
</code>

and here is persistence.js code referenced above in head -- should I have added to body instead?

<code>
function saveCookie(){
    $('form').each(function(i){
        x = $(this).attr('name');
        str = $(this).serialize();
        $.cookie(x, str, {expiers : 2});
    });
}
 
function restoreCookie(){
    $('form').each(function(i){
        x = $(this).attr('name');
        str = $.cookie(x);
        data = str.split('&');
        $(data).each(function(element) {
            a = this.split('=');
            $('input[name="'+a[0]+'"]').val(decodeURIComponent(a[1]));
        })
    });
}
function resetForm(contactForm){
    $(contactForm).reset();
    $.removeCookie(contactForm);
}
$(document).ready(function(e){
    restoreCookie();
    $('a').click(function(e){
        e.preventDefault();
        saveCookie();
        window.location = $(this).attr('href');
    });
});

Open in new window

I have difficulty testing as I have to use satellite Internet which has issues with persistence anyway.

Thanks for any assistance with this matter.
Bette
0
Comment
Question by:Bette Lamore
  • 7
  • 6
15 Comments
 
LVL 53

Expert Comment

by:COBOLdinosaur
ID: 40216973
If you have a problem with persistence any way because of the connection, why not handle the problem from the server by retaining the information in the session variables and use them to repopulate the form when you generate a response?

Cd&
0
 

Author Comment

by:Bette Lamore
ID: 40221549
Thanks for you responses, Gary and COBALdinoaur. Sorry for delay -- away for a couple of days.
I lease a portion of a server and cannot use a Java or Asp.NET code on it due to restrictions. When I get enough clients to justify leasing a total server, then I can do what I want -- frustrating yet I am working on a MS degree and only have my pre-existing clients -- low key and no expansion right now. The persistence protocols I was taught involve Java -- where would I look if there are other ways to do this?
0
 
LVL 33

Expert Comment

by:Slick812
ID: 40227457
greetings woalamore, , You have this as your <form> action -
action="http://www.thumbsupproduction.com/inc/mail/fmj.php"

which looks to me as your server does PHP language code. So as I have done this, I considered Three options,
One : to use the php $_SESSION[ ] array to store ALL form data -
    session_start();
    $_SESSION['input1'] = $_POST['input1'];

however this may need some special browser conditions to be very useful.

Two: use a browser set cookie to store all form inputs in a cookie, but again, this is usually necessary only for more varied browser (javascript) form variations.

Three: what I mostly do is to just get the Input values from the PHP $_POST[ ] and just have an if(error) test, and if there is an error, then write the php input values to the form inputs on the sent page with the verification error.
Below is some code that is overly simple, but does show the basic PHP to put Input values BACK into inputs IF there is an error detected or the values can not be accepted by the php requirements.

<?php
$error= '';
if(count($_POST)>0){
  $rname = (empty($_POST['rname'])) ? '' : $_POST['rname'];
  $email = (empty($_POST['email'])) ? '' : $_POST['email'];
  if (strlen($rname) < 5) $error = 'Verification ERROR, name less than 5';
  if (strlen($email) < 8) $error = 'Verification ERROR, email less than 8';
  }
?>
<html><head><title>form</title></head><body><?php if($error) echo $error,'<br />' ?>
please fill form -<br />
<form name="cForm" method="post" id="cForm" action="fmj.php" onsubmit="return verify(this)">
<input type="text" name="rname" id="rn" maxlength="20" size="20" value="<?php if($error) echo $rname; ?>"/>
<input type="text" name="email" id="em" maxlength="40" size="20" value="<?php if($error) echo $email; ?>"/>
</form>
</body</html>

Open in new window


as I said if the PHP code is not availible to you, you can write the input values to a browser cookie CSV string and read the cookie and use javascript to place values back into the inputs, but it may not be as easy as the php.
0
 

Author Comment

by:Bette Lamore
ID: 40227892
Thank you so much for responding, slick812.
The fmj script is only to check the verification code word (a simplistic capcha as there is no need for more sophistication). The code is just:
<?php 
	//if ('fmj.php' == basename($_SERVER['SCRIPT_FILENAME']))
		//die ('Please do not load this page directly. Thanks!');
   	$entryVar = trim($_POST['verCode']);
	if ($entryVar != "smile") {
		echo "
			<script type='text/javascript'>
				<!-- // 
					alert('Sorry, your verification code did not match; please use the Back button on your browser if you are not returned to the form.');
					history.back();
				// -->
			</script>
		";
	}
	else {
		require_once("/home/tup/adb/inc.formmail.php"); 
	}
?>

Open in new window


I already have a verifyMe function:
function verifyMe() {
var msg='';
	if(document.getElementById('realname').value=='') {
		msg+='- Name\n\n';
	}
	if(document.getElementById('emailaddy').value=='') {
		msg+='- Email Address\n\n';
	}
var emailaddy=document.getElementById('emailaddy').value;
	if(!(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/igm.test(emailaddy))) {
    	msg+='- Invalid Email Address: '+emailaddy+'\n\n';
	}

var phone=document.getElementById('dayphone').value;
	if(!(/^\d{3}-\d{3}-\d{4}$/.test(phone)) && !(document.getElementById('dayphone').value=='')) { 
    	msg+='- Day Phone Number or Format\n\n';
	}

var phone=document.getElementById('evephone').value;
	if(!(/^\d{3}-\d{3}-\d{4}$/.test(phone)) && !(document.getElementById('evephone').value=='')) { 
    	msg+='- Evening Phone Number or Format\n\n';
	}

	if(msg!='') {
		alert('Oooops! Please re-enter your information re:\n\n'+ msg);
		return false;
	}
	else {
		return true 
	}
}

Open in new window

I am unsure about what to add in the form or fmj.php to make the information in the form persist when the user is sent to an error page due to the verification code mistakenly omitted or entered wrong. The info gathered in the form is too much, I believe, to store in a browser cookie and I am unfamiliar with PHP coding, other than to use the form.php or fmj script.
Thanks for any help on this
Bette
0
 
LVL 33

Expert Comment

by:Slick812
ID: 40228037
OK, If using PHP script is not possible, then javascript to cookie is an option, , But I am confused at this point, because you already have some javascript functions to save and get cookie to form elemens as this one -

function saveCookie(){
    $('form').each(function(i){
        x = $(this).attr('name');
        str = $(this).serialize();
        $.cookie(x, str, {expiers : 2});
    });
}

although the Jquery element property access of this code is very out of date, , it does make a cookie with name "contactForm" to have all elements values as a CSV URL string from this -
str = $(this).serialize();

so it seems that you already have some code in JS for this, so I wonder where you have problems, , as if this JS cookie function does not work, , OR is there some problem with the procedure that does the "error page due to the verification code mistakenly omitted", , so I am not seeing the whole picture of your problem? ? sorry I do not catch the trouble. Can you tell us about that happends to the page change that causes the Form to lose it's entries with the JS code of  saveCookie( )  and  restoreCookie( )   ? ?
0
 

Author Comment

by:Bette Lamore
ID: 40228181
Thanks again Slick812
Although I have the persistence.js in the head, I realized that where it said 'form' I should have probably replaced it with contactForm with no single quotes so I uploaded the changed version. No change. Then I thought that perhaps I also should have changed the 'contact' in the submit line in my contact form to contactForm, although the prototype just used the first part of the form name. I uploaded and no success.

Always when I have used JS or Java I have had to call the function, yet in the template I used here, the only call to restore the values is in the original function -- there is no line of code in the form that calls this function. Am I missing something? (All the code is in my original post with the changes made as specified here and subsequent posts.) It has been 2 1/2 years since I took any programming and have had very little chance to use it since then as I started my MS in GIS degree -- I am very rusty -- sorry -- you will have to be specific with me.
Thank you so much for your help!
Bette
0
 
LVL 33

Expert Comment

by:Slick812
ID: 40230134
OK, I was not succesful in finding out how to properly use the jquery persistence.js, this is the example they have in the test page that is with the jquery.persistence.js -

jQuery('input,select,textarea').persist();

which will place ALL inputs, selects and textareas into cookie evaluation contents, and then retrive the cookies when it loads, and place values in hidden and text inputs, and check-uncheck radios and checkboxes.

your restoreCookie() function as -
function restoreCookie(){
    $('form').each(function(i){
        x = $(this).attr('name');
        str = $.cookie(x);
        data = str.split('&');
        $(data).each(function(element) {
            a = this.split('=');
            $('input[name="'+a[0]+'"]').val(decodeURIComponent(a[1]));
        })
    });
}

is entirely inadaquite to preserve any checkboxs that you have in your form, as it does not have any info about what is checked, especially if you use array name calls like "info[]" as you do. So I do not think you can use the cookie functions you have - saveCookie()  and  restoreCookie()

My main problem with the jquery persistence.js  is trying to figure out how to "start" and "stop" it's actions as needed in your form page I would guess that this -
jQuery('input:text,input:checkbox,textarea').persist();
would both save and restore ALL inputs of text checkbox and textarea  ,  , , and  this -
jQuery('input:text,input:checkbox,textarea').unpersist();
might remove the persistent cookies.

I am very sort of time today, so I can not do the testing needed for this persistence thing.
0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 

Author Comment

by:Bette Lamore
ID: 40230186
OK, slick812, thanks for telling me that this will not work so I will not waste my time on it anymore. Do you by chance have a PHP script that will collect my info and restore it upon returning to the form page? Or at least a link to a page where I can get one? After your response I will give you all the points, or at least split them with you if someone else comes up with a script beforehand. I really appreciate all your help!
Bette
0
 
LVL 33

Expert Comment

by:Slick812
ID: 40230799
I did not say that the  jQuery('input:text,input:checkbox,textarea').persist();  would not work, as far as I can tell it will always restore the form elements listed from the cookies, however if the PHP accepts the the form input, and the user goes back to the FORM page expecting a blank form, the cookies will still be there, and it will fill out the form again as it was before. But I think you could get around that.

As far as the PHP goes, you can have a session store for the form, so even if there is an error page, before going back to the Form page you could still refill the form text and checks as they were before.

As far as doing the PHP code, you have this in your PHP -
<?php 
//if ('fmj.php' == basename($_SERVER['SCRIPT_FILENAME'])) die ('Please do not load this page directly. Thanks!');
  $entryVar = trim($_POST['verCode']);
  if ($entryVar != "smile") {
    echo "<script type='text/javascript'>
      alert('Sorry, your verification code did not match; please use the Back button on your browser if you are not returned to the form.');
  history.back();
</script>";
    } else {
    require_once("/home/tup/adb/inc.formmail.php"); 
    }
?>

Open in new window

I am not sure I can work with this PHP to do much useful alterations, I am very puzzled about the capcha "error" page as javascript -

 echo "<script type='text/javascript'>
      alert('Sorry, your verification code did not match;
 please use the Back button on your browser if you are not returned to the form.');
  history.back();
</script>";

I do not believe that this is a good approach to display errors on a web form page with all of the more effective CSS-HTML options now commonly used for html5 pages in mobil. I do not believe it to be correct HTML for this kind of thing?
I am trying to have this be as little coding for alterations as possible, to save both of us time. But your request of a one-size-fits-all "Do you by chance have a PHP script that will collect my info and restore it upon returning to the form page?" does not seem to be a thing, at least as far as I know?

as I have shown before this for an input -
<input type="text"  name="realname" id="realname"
   value="<?php if($error) echo $rname; ?>" />

please notice the php as - <?php if($error) echo $rname; ?>
which will write the previous value there from the php $_POST
Almost all Form pages that have Server (php) rejection errors, display the FORM page Again, but with the ERROR reported at the top of the page, or with the FORM itself, so the user can reference the Errors as they fix their form entries.
0
 
LVL 33

Expert Comment

by:Slick812
ID: 40232442
OK, I made some time today at lunch to work on this thing and this is what I came up with -
<!doctype html><head><title>Form Persistence</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery.cookie.js"></script>
<script type="text/javascript" src="jquery.persist.js"></script>
<script>
jQuery(document).ready(function() {
  jQuery('input:text,input:checkbox,textarea').persist();
  });
  
function verifyMe() {
var msg='';
if(document.getElementById('realname').value.length<2) {msg+='- Name to short,\n\n';}
var email=document.getElementById('emailaddy');
if(email.value.length<7) {msg+='- Email Address Must Have 7 charaters,\n\n';}
  else if(!(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/igm.test(email.value))) {
    msg+='- Invalid charaters in Email Address: '+email.value+',\n\n';
    }

var phone=document.getElementById('dayphone');
if((phone.value.length!=12) || !(/^\d{3}-\d{3}-\d{4}$/.test(phone.value))) { msg+='- Day Phone Number or Format,\n\n';}

phone=document.getElementById('evephone');
if((phone.value.length!=12) || !(/^\d{3}-\d{3}-\d{4}$/.test(phone.value))) { msg+='- Evening Phone Number or Format,\n\n';}

if(msg) {
  alert('Oooops! Please re-enter your information re:\n\n'+ msg);
  return false;
  } else {return true }
}
</script>
<style>
.fm{width:34em;padding:5px;border:2px solid #00c;}
.currentField{background-color:#dfd;}
.changedField{background-color:#eef;}
</style>
</head><body><h3>Form Persistence</h3><?php if(isset($_POST['subject'])) echo '<h2>Post was RECEIVED!</h2>'; ?>

<form class="fm" name="contactForm" method="post" id="contactForm" action="formp.php" onsubmit="return verifyMe()">
  <input type="hidden" name="subject" value="Contact Form" />
  <input type="hidden" name="recipients" value="form" />
  <input type="hidden" name="derive_fields" value="IP = REMOTE_ADDR, Browser = HTTP_USER_AGENT, Referrer = HTTP_REFERER" />
  <input type="hidden" name="mail_options" value="HTMLTemplate=mail.contact.htm,TemplateMissing=N/A,KeepLines" />
  <div align="center"> <font color="#000000"  size="3em" face="Open Sans, sans-serif"><strong>Contact Form</strong></font> <br />
  <br />
  </div>
  <div align="left"><font face="Open Sans, sans-serif" size="2em"><strong>
  <font color="#ff0000">*</font><font color="#000000"><em> Name</em>
  <input type="text"  name="realname" id="realname" maxlength="20" size="20" 
  onfocus="this.className='currentField'" 
  onchange="this.className='changedField'" />&nbsp;&nbsp;<font color="#FF0000">*</font><em>Email</em>
  <input type="text" name="email" id="emailaddy" maxlength="40" size="20" 
  onfocus="this.className='currentField'" 
  onchange="this.className='changedField'" />
         <br /><center>
          <font color="#ff0000"><em>* Required Fields</em></font></font></strong></font></center> 

</div>
  <p align="left"><font color="#000000"  size="2em" face="Open Sans, sans-serif"><strong>
I am interested in the following (check all that apply):</strong><br />
          <input name="info[]" type="checkbox" value="dvd" 
				onfocus="this.className='currentField'" 
				onchange="this.className='changedField'" />
          DVD Production (Please describe in Comment section below)<br />
          <input name="info[]" type="checkbox" value="BunnyDVD" 
				onfocus="this.className='currentField'" 
				onchange="this.className='changedField'" />
          DVD of Against all Odds<br />
          <br />
          Mailing Address :
          <input type="text" name="Address" maxlength="30" size="30" 
				onfocus="this.className='currentField'" 
				onchange="this.className='changedField'" />
          <br />
          <br />
          City:
          <input type="text" name="City" maxlength="30" size="30" 
				onfocus="this.className='currentField'" 
				onchange="this.className='changedField'" />
         &nbsp;&nbsp;&nbsp
          State:
          <input type="text" name="State" maxlength="4" size="4" 
				onfocus="this.className='currentField'" 
				onchange="this.className='changedField'" />
          &nbsp;&nbsp;&nbspZip Code:
          <input type="text" name="ZipCode" size="8" maxlength="8" 
				onfocus="this.className='currentField'" 
				onchange="this.className='changedField'" />
          <br />
          <br />
          Day Phone # (xxx-xxx-xxxx):
          <input type="text" name="dayphone" id="dayphone" size="14" maxlength="14" 
				onfocus="this.className='currentField'" 
				onchange="this.className='changedField'" />
          <br /> 
          Evening Phone # (xxx-xxx-xxxx):
          <input type="text" name="evephone" id="evephone" size="14" maxlength="14" 
				onfocus="this.className='currentField'" 
				onchange="this.className='changedField'" />
          <br /><br />
          Website Address:
          <input type="text" name="Website" size="14" maxlength="50" onfocus="this.className='currentField'" onchange="this.className='changedField'" />
          <br />
          </font><font color="#000000"  size="2em" face="Trebuchet MS, Arial, sans-serif"><br />
          <strong>Please let us know how you happened to visit us</strong>:<br />
          <input name="referred[]" type="checkbox" 
				value="Google" 
				onfocus="this.className='currentField'" 
				onchange="this.className='changedField'" />
          Google<br />
          <input name="referred[]"  type="checkbox" 
				value="youtube" 
				onfocus="this.className='currentField'" 
				onchange="this.className='changedField'" />
          YouTube<br />
          <input name="referred[]" type="checkbox"  
				value="LinkedIn" 
				onfocus="this.className='currentField'" 
				onchange="this.className='changedField'" />
          LinkedIn<br />
          <input name="referred[]"  type="checkbox"  
				value="bing" 
				onfocus="this.className='currentField'" 
				onchange="this.className='changedField'" />
          Bing<br />
          <input name="referred[]" type="checkbox" 
				value="Other Search Engine" 
				onfocus="this.className='currentField'" 
				onchange="this.className='changedField'" />
          Other Search Engine (please list in comment section)<br />
          <input name="referred[]"  type="checkbox"  
				value="other" 
				onfocus="this.className='currentField'" 
				onchange="this.className='changedField'" />
          Other (Please list in Comment section)<br />
          </font></p>
        <p align="center"><strong> <font color="#000000" size="3em">Comments / Feedback</font></strong><br />
          <textarea cols="48" name="Notes" rows="10" ></textarea>
        </p>
        <p align="left"><font color="#000000" face="Open Sans,sans-serif" size="2em"><strong>
		<font color="#ff0000"> *</font>Enter the code word: 
		<font color="#ff0000"><em>smile</em></font></strong></font>
          <input type="text" name="verCode" id="verCode" size="32" maxlength="16" value="" />
        </p>
        <p>&nbsp;</p>
        <p align="center" ><font color="#000000"  face="Open Sans, sans-serif" size="3em"><strong> 

Please click the Submit button once to send form.</strong></font><br />
          <input type="submit" name="contact" value="Submit" />
          <input type="reset"  onclick="resetForm('contactForm')" value="Reset Form" />
          <br />
        </p>
</form>

</body></html>

Open in new window

I got the jquery.cookie.js  and the  jquery.persist.js  from the Google API library, I could NOT find ANY documentation for the jquery.persist.js , so I just used the basic  .persist()  function, but it does Preserve all the form elements needed for this.  I believe that it does NOT persist after the browser closes, the cookies are only till the close.

Just so you know I changed the VERIFY function to be more better, I do NOT have time to change the EMAIL verify -
   if(!(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/igm.test(email.value)))

to something that works, this does NOT filter the emails as it should.
please test this out you need to add this --

jQuery(document).ready(function() {
  jQuery('input:text,input:checkbox,textarea').persist();
  });

to this script in the top section <head> of the document, and no matter if you leave the page, and go back it keeps the values there
please test this out in several browsers and see if it will go for you
0
 

Author Comment

by:Bette Lamore
ID: 40233251
Thank you once again slick812 yet it still doesn't work.
I searched and searched and was unable to find jquery.persist.js  and then thought that perhaps you just renamed the persistence.jquery.js which I did locate so I downloaded it as well as the persistence.js which was located in the same master file which said it had to be loaded as well.

This is the code I have, just modifying yours slightly:
<!doctype html><head><title>Form Persistence</title>
<script type="text/javascript" src="jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="jquery.cookie.js"></script>
<script type="text/javascript" src="persistence.js"></script>
<script type="text/javascript" src="persistence.jquery.js"></script>

<script>
jQuery(document).ready(function() {
  jQuery('input:text,input:checkbox,textarea').persist();
  });
  
function verifyMe() {
var msg='';
	if(document.getElementById('realname').value.length<2) {
		msg+='- Name too short,\n\n';
	}
	if(document.getElementById('emailaddy').value=='') {
		msg+='- Email Address\n\n';
	}

var emailaddy=document.getElementById('emailaddy').value;
	if(!(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/igm.test(emailaddy))) {
    	msg+='- Invalid Email Address: '+emailaddy+'\n\n';
	}

var phone=document.getElementById('dayphone').value;
	if(!(/^\d{3}-\d{3}-\d{4}$/.test(phone)) && !(document.getElementById('dayphone').value=='')) { 
    	msg+='- Day Phone Number or Format\n\n';
	}

var phone=document.getElementById('evephone').value;
	if(!(/^\d{3}-\d{3}-\d{4}$/.test(phone)) && !(document.getElementById('evephone').value=='')) { 
    	msg+='- Evening Phone Number or Format\n\n';
	}

	if(msg!='') {
		alert('Oooops! Please re-enter your information re:\n\n'+ msg);
		return false;
	}
	else {
		return true 
	}
}
</script>
<style>
.fm{width:34em;padding:5px;border:2px solid #00c;}
.currentField{background-color:#dfd;}
.changedField{background-color:#eef;}
</style>
</head><body><h3>Form Persistence</h3>

<form class="fm" name="contactForm" method="post" id="contactForm" action="http://www.thumbsupproduction.com/inc/mail/fmj.php" onSubmit="return verifyMe()">
  <input type="hidden" name="subject" value="Contact Form" />
  <input type="hidden" name="recipients" value="form" />
  <input type="hidden" name="derive_fields" value="IP = REMOTE_ADDR, Browser = HTTP_USER_AGENT, Referrer = HTTP_REFERER" />
  <input type="hidden" name="mail_options" value="HTMLTemplate=mail.contact.htm,TemplateMissing=N/A,KeepLines" />
  <div align="center"> <font color="#000000"  size="3em" face="Open Sans, sans-serif"><strong>Contact Form</strong></font> <br />
  <br />
  </div>
  <div align="left"><font face="Open Sans, sans-serif" size="2em"><strong>
  <font color="#ff0000">*</font><font color="#000000"><em> Name</em>
  <input type="text"  name="realname" id="realname" maxlength="20" size="20" 
  onfocus="this.className='currentField'" 
  onchange="this.className='changedField'" />&nbsp;&nbsp;<font color="#FF0000">*</font><em>Email</em>
  <input type="text" name="email" id="emailaddy" maxlength="40" size="20" 
  onfocus="this.className='currentField'" 
  onchange="this.className='changedField'" />
         <br /><center>
          <font color="#ff0000"><em>* Required Fields</em></font></font></strong></font></center> 

</div>
  <p align="left"><font color="#000000"  size="2em" face="Open Sans, sans-serif"><strong>
I am interested in the following (check all that apply):</strong><br />
          <input name="info[]" type="checkbox" value="dvd" 
				onfocus="this.className='currentField'" 
				onchange="this.className='changedField'" />
          DVD Production (Please describe in Comment section below)<br />
          <input name="info[]" type="checkbox" value="BunnyDVD" 
				onfocus="this.className='currentField'" 
				onchange="this.className='changedField'" />
          DVD of Against all Odds<br />
          <br />
          Mailing Address :
          <input type="text" name="Address" maxlength="30" size="30" 
				onfocus="this.className='currentField'" 
				onchange="this.className='changedField'" />
          <br />
          <br />
          City:
          <input type="text" name="City" maxlength="30" size="30" 
				onfocus="this.className='currentField'" 
				onchange="this.className='changedField'" />
         &nbsp;&nbsp;&nbsp
          State:
          <input type="text" name="State" maxlength="4" size="4" 
				onfocus="this.className='currentField'" 
				onchange="this.className='changedField'" />
          &nbsp;&nbsp;&nbspZip Code:
          <input type="text" name="ZipCode" size="8" maxlength="8" 
				onfocus="this.className='currentField'" 
				onchange="this.className='changedField'" />
          <br />
          <br />
          Day Phone # (xxx-xxx-xxxx):
          <input type="text" name="dayphone" id="dayphone" size="14" maxlength="14" 
				onfocus="this.className='currentField'" 
				onchange="this.className='changedField'" />
          <br /> 
          Evening Phone # (xxx-xxx-xxxx):
          <input type="text" name="evephone" id="evephone" size="14" maxlength="14" 
				onfocus="this.className='currentField'" 
				onchange="this.className='changedField'" />
          <br /><br />
          Website Address:
          <input type="text" name="Website" size="14" maxlength="50" onFocus="this.className='currentField'" onChange="this.className='changedField'" />
          <br />
          </font><font color="#000000"  size="2em" face="Trebuchet MS, Arial, sans-serif"><br />
          <strong>Please let us know how you happened to visit us</strong>:<br />
          <input name="referred[]" type="checkbox" 
				value="Google" 
				onfocus="this.className='currentField'" 
				onchange="this.className='changedField'" />
          Google<br />
          <input name="referred[]"  type="checkbox" 
				value="youtube" 
				onfocus="this.className='currentField'" 
				onchange="this.className='changedField'" />
          YouTube<br />
          <input name="referred[]" type="checkbox"  
				value="LinkedIn" 
				onfocus="this.className='currentField'" 
				onchange="this.className='changedField'" />
          LinkedIn<br />
          <input name="referred[]"  type="checkbox"  
				value="bing" 
				onfocus="this.className='currentField'" 
				onchange="this.className='changedField'" />
          Bing<br />
          <input name="referred[]" type="checkbox" 
				value="Other Search Engine" 
				onfocus="this.className='currentField'" 
				onchange="this.className='changedField'" />
          Other Search Engine (please list in comment section)<br />
          <input name="referred[]"  type="checkbox"  
				value="other" 
				onfocus="this.className='currentField'" 
				onchange="this.className='changedField'" />
          Other (Please list in Comment section)<br />
          </font></p>
        <p align="center"><strong> <font color="#000000" size="3em">Comments / Feedback</font></strong><br />
          <textarea cols="48" name="Notes" rows="10" ></textarea>
        </p>
        <p align="left"><font color="#000000" face="Open Sans,sans-serif" size="2em"><strong>
		<font color="#ff0000"> *</font>Enter the code word: 
		<font color="#ff0000"><em>smile</em></font></strong></font>
          <input type="text" name="verCode" id="verCode" size="32" maxlength="16" value="" />
        </p>
        <p>&nbsp;</p>
        <p align="center" ><font color="#000000"  face="Open Sans, sans-serif" size="3em"><strong> 

Please click the Submit button once to send form.</strong></font><br />
          <input type="submit" name="contact" value="Submit" />
          <input type="reset"  onclick="resetForm('contactForm')" value="Reset Form" />
          <br />
        </p>
</form>
</body></html>

Open in new window


I already put my fmj.php code above which returns the user back to the form if he has not entered the word "smile." That is my problem in that when the user returns to the form, all the fields are blank instead of populated with the data he entered.

I so appreciate the work you have done this far -- wish I could award more than 500 points.
Bette
0
 
LVL 33

Accepted Solution

by:
Slick812 earned 500 total points
ID: 40234386
????, I told you the  jquery.persist.js was at the google API, AND it does NOT have anything to do with any other persistence JS like  persistence.js  or persistence.jquery.js  
I am not sure about how many so called "persistence JavaScript" add-on there are, but there are many, I simply do not have time to investigate any of these, I used the jquery.persist.js  because you have the  jquery.cookie.js  in your first code for this, and I searched for some jquery "persistence" to preserve Form entries, and the Google API library yielded the jquery.persist.js that required YOUR entry of jquery.cookie.js so I used that one. I did find several JS libraries named  persistence.js  that DID NOT USE ANY Jquery and did not need jquery.cookie.js, but your code work is so undefined and not good that I just assumed the jquery.persist.js could do the job, as you gave no other indications, the code I have for the jquery.persist.js is here -
/*
	jquery-persist 201203*pike
	
	persist form values in cookies
	
	example usage:
	
		$('input,select,textarea').persist(options);
		
		$('input,select,textarea').unpersist(options);
		
	options
	
		context 	: 'def',		// a context or namespace for each field
		replace		: true,			// replace existing field contents if any
		cookie		: 'jqpersist',	// cookies basename
		path		: '/',			// cookie path
		domain		: null,			// cookie domain
		expires		: null,			// cookie expiry (eg 365)

*/



jQuery.fn.persist = function(options) {

	options = jQuery.extend({}, jQuery.persist.defaults, options);
	return jQuery(this).each(function() {
		var name = $(this).attr('name');
		var val =jQuery.persistedValue(name,options);
		if(val) {
			switch(this.tagName.toLowerCase()) {
				case  'input':
					switch($(this).attr('type')) {
						case 'radio':
							// if we can replace anything or there are no checked radio buttons
							if (options['replace']||$(this).parents('form').eq(0).find('input[name="'+name+'"]:checked').size()==0) {
								$(this).parents('form').eq(0)
									.find('input[name="'+name+'"]').each(function() {
									this.checked = ($(this).val()==val);
								});
							}
							break;
						case 'checkbox':
							var vals = val.split(jQuery.persist.arrsep);
							$(this).parents('form').eq(0)
								.find('input[name="'+name+'"]').each(function() {
								// if we can replace this value or it was checked by itself
								this.checked = ((jQuery.inArray($(this).val(),vals)!=-1)||(this.checked&&!options['replace']));
							});
							break;
						default:
							// if we can replace it or it is empty or 0
							if (options['replace']||!$(this).val()) {
								$(this).val(val);
							}
					}
					break;
				case 'select':
					if ($(this).attr('multiple')) {
						var vals = val.split(jQuery.persist.arrsep);
						$(this).children('option').each(function() {
							// if we can replace this value or it was selected by itself
							this.selected = ((jQuery.inArray($(this).val(),vals)!=-1)||(this.selected&&!options['replace']));
						});
					} else {
						// if we can replace it or it is empty or 0
						if (options['replace']||!$(this).val()) {
							$(this).val(val);
						}
					}
					break;	
				default:
					// if we can replace it or it is empty or 0
					if (options['replace']||!$(this).val()) {
						$(this).val(val);
					}
			}
		}
	}).on('change.persist', function(){
		var name = $(this).attr('name');
		switch(this.tagName.toLowerCase()) {
			case  'input':
				switch($(this).attr('type')) {
					case "checkbox":
						var vals = [];
						$(this).parents('form').eq(0)
							.find('input[name="'+name+'"]').each(function() {
							if (this.checked) vals.push($(this).val());
						});
						jQuery.persistValue(name,vals.join(jQuery.persist.arrsep),options);
						break;
					default:
						jQuery.persistValue(name, $(this).val(), options);
				}
				break;
			case "select":
				if ($(this).attr('multiple')) {
					var vals = [];
					$(this).children('option').each(function() {
						if (this.selected) vals.push($(this).val());
					});
					jQuery.persistValue(name,vals.join(jQuery.persist.arrsep),options);
				} else {
					jQuery.persistValue(name, $(this).val(), options);
				}
				break;
			default:
				jQuery.persistValue(name, $(this).val(), options);
		}
	});
}

jQuery.fn.unpersist = function(options) {
	options = jQuery.extend({}, jQuery.persist.defaults, options);
	$(this).each(function() {
		var name = $(this).attr('name');
		jQuery.persistValue(name,null,options);
	}).off('change.persist');
	return $(this);
}

jQuery.persistValue = function (key, value, options) {

	options = jQuery.extend({}, jQuery.persist.defaults, options);
	var ctx = options['context'];
	
	if (!jQuery.persist.keys.length) {
		if (!jQuery.persistInit(options)) return false;
	}
	var idx = jQuery.inArray(ctx+jQuery.persist.ctxsep+key,jQuery.persist.keys);
	if (idx!=-1) {	
		if (value === null || value === undefined) {
			// remove value
			if (jQuery.persist.debug) console.log('unpersist '+key);
			jQuery.persist.keys.splice(idx,1);	
			jQuery.persist.vals.splice(idx,1);	
		} else {
			if (jQuery.persist.debug) console.log('persist '+key+':'+value);
			jQuery.persist.vals[idx]=value;
		}
	} else {
		if (!(value === null || value === undefined)) {
			if (jQuery.persist.debug) console.log('add persist '+key+':'+value);
			jQuery.persist.keys.push(ctx+jQuery.persist.ctxsep+key);
			jQuery.persist.vals.push(value);
		}
	}
	if (jQuery.persist.keys.length) {
		// store keys/vals
		jQuery.cookie(options.cookie+'_keys',jQuery.persist.keys.join(jQuery.persist.elmsep),options);
		jQuery.cookie(options.cookie+'_vals',jQuery.persist.vals.join(jQuery.persist.elmsep),options);
	} else {
		// remove the whole cookie
		options['expire']=null;
		jQuery.cookie(options.cookie+'_keys','',options);
		jQuery.cookie(options.cookie+'_vals','',options);
	}
} 

	
jQuery.persistedValue = function(key,options) {

	options = jQuery.extend({}, jQuery.persist.defaults, options);
	var ctx = options['context'];
	
	if (!jQuery.persist.keys.length) {
		if (!jQuery.persistInit(options)) return false;
	}
	
	var idx = jQuery.inArray(ctx+jQuery.persist.ctxsep+key,jQuery.persist.keys);
	if (idx!=-1) {	
		if (jQuery.persist.debug) console.log('persisted '+key+':'+ jQuery.persist.vals[idx]);
		return jQuery.persist.vals[idx];
	} else {
		if (jQuery.persist.debug) console.log('persisted '+key+': nop');
		return null; //undefined
	}

}

jQuery.persistInit = function(options) {
	if (jQuery.persist.debug) console.log('persist init ');	
	options = jQuery.extend({}, jQuery.persist.defaults, options);
	var skeys = $.cookie(options.cookie+'_keys')  || '';
	var svals = $.cookie(options.cookie+'_vals') || '';
	jQuery.persist.keys = skeys.split(jQuery.persist.elmsep); 
	jQuery.persist.vals = svals.split(jQuery.persist.elmsep);
	if (jQuery.persist.keys.length!=jQuery.persist.vals.length) {
		// this should never happen
		alert('persist error - erasing');
		options['expire']=null;
		jQuery.cookie(options.cookie+'_keys',null,options);
		jQuery.cookie(options.cookie+'_vals',null,options);
		jQuery.persist.keys = []; 
		jQuery.persist.vals = []; 
		return false;
	}
	if (jQuery.persist.debug) console.log(jQuery.persist.keys);
	if (jQuery.persist.debug) console.log(jQuery.persist.vals);
	return true;
}

jQuery.persist = {
	debug	: false,
	defaults: {
		context 	: 'def', // a context or namespace for each field
		replace		: true,	// replace existing field contents if any
		cookie		: 'jqpersist', // cookies basename
		path		: '/',	// cookie path
		domain		: null,	// cookie domain
		expires		: null // cookie expiry (eg 365)
	},
	elmsep	: '##',
	ctxsep	: '::',
	arrsep	: '//',
	keys		: [],
	vals		: []
};

Open in new window

 please put this in a text file and name it   -
jquery.persist.js
0
 
LVL 33

Expert Comment

by:Slick812
ID: 40234408
I spent some time on the verifyMe(), and you did not use it.  I will tell you that your HTML used in this is very out of date as the <font> tag is no longer used, there are many CSS, even the old CSS2, that can make this a better user friendly presentation. You would do well if you are developing this web site, to get someone with knowledge to help with the javascript and CSS presentation.
0
 

Author Comment

by:Bette Lamore
ID: 40235291
I use CSS exclusively for my xhtml pages except for this very old script -- if it ain't broke, don't fix it. I keep using it because it is simple and works. I know I will eventually have to update it -- just time is an issue with a MS program in GIS right now and college for the last 5 years. I appreciate your pointing out that it is outdated -- already knew that.

Your verifyMe script created an error with the phone numbers - in my original, there is no error if nothing is entered; there was only an error message if format was bad, You stated you did not change email verification so I used my old for now -- and I did change your verification for the name.

If you go to www.thumbsupproduction.com I believe you will readily see that my pages up all updated with js and CSS. IT was only the persistence that I was having difficulty with.

I searched on the Google API pages and did not find your script as written. As you renamed my fmj.php script to formp.php I thought that perhaps you renamed the persistence script I found as well. Thank you for providing me with the script -- a link would have sufficed as well.

Thank you for your work on this. I have awarded your points.
Bette
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Envision that you are chipping away at another e-business site with a team of pundit developers and designers. Everything seems, by all accounts, to be going easily.
Although it can be difficult to imagine, someday your child will have a career of his or her own. He or she will likely start a family, buy a home and start having their own children. So, while being a kid is still extremely important, it’s also …
Any person in technology especially those working for big companies should at least know about the basics of web accessibility. Believe it or not there are even laws in place that require businesses to provide such means for the disabled and aging p…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now