I am creating a form that you don’t actually submit in order to allow people to download files. You select different options with radio buttons and drop-down menus and then use that information to “show/hide” divs with javascript. That part works, but if the user leaves the page and then comes back, the data can be somewhat misleading. One radio button may be checked, but the corresponding div that was showing before you left the page is not (it was set to “display:block;” in css with the “onclick” or “onchange” depending on which choice on the form caused it to appear).

I know that I need to set a session cookie to save the values on the form, but it is a bit more complicated because I need to set divs to “display:block;” or “display:none;” depending on what the values of the form fields are.

Would anyone have any suggestions of where I could go to learn more about how to do this? I’m a novice at javascript. Since I am not submitting the form, I can’t use PHP.

Any advice would be appreciated.

Recommended Answers

All 9 Replies

Sgweaver,

As I understand it, all you need to do is to ensure, on page load/reload, that your divs are correctly shown/hidden in accordance with the state of various radio buttons and pulldown menus.

You should be able to get away without setting a session cookie.

You can make a "scan" function that scans your form elements, tests their state and sets divs accordingly. Then you arrange for the scan function to ba called when the window loads/reloads so it will guarantee that your divs are always in synchronisation with your controls.

This technique has the advantage that it will also work during in normal user interaction by calling scan in response to relevant user events.

In my demo below, I have also arranged for the "bindings" between controls and divs to be specified in the HTML, not in the JavaScript, which may make the page easier to develop/maintain.

I have tested in IE6 and Moz 3.0.7 (both under win 2000) it works in both! On going back to the page, controls and divs all return to their previous states.

Here it is:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitled</title>
<style type="text/css">
#controls, #divs { margin-bottom:12px; width:160px; padding:10px; border:1px solid #999999; }
#controls h1, #divs h1 { margin:2px 0; padding:3px 0; font-size:9pt; text-align:center; background-color:#e0e0e0; }
form { margin:0; }
.showHide { display:none; margin:3px 0; padding:3px; text-align:center; }
.red { background-color:#FF9999; }
.green { background-color:#99FF99; }
.blue { background-color:#9999FF; }

</style>

<script language="JavaScript" type="text/javascript">
function scan(){
	var inputElements = document.getElementsByTagName('input');
	for(var i=0; i<inputElements.length; i++){
		if( inputElements[i].getAttribute('type') == 'radio' && inputElements[i].className == 'scanMe' ){
			var div = document.getElementById( inputElements[i].getAttribute('divId') );
			div.style.display = (inputElements[i].checked) ? 'block' : 'none';
		}
	}
	var optionElements = document.getElementsByTagName('option');
	for(var i=0; i<optionElements.length; i++){
		if( optionElements[i].className == 'scanMe' ){
			var div = document.getElementById( optionElements[i].getAttribute('divId') );
			var selectedOption = optionElements[i].parentNode[optionElements[i].parentNode.selectedIndex];
			div.style.display = (selectedOption == optionElements[i]) ? 'block' : 'none';
		}
	}
	return false;
}

onload = function(){
	scan();
}
</script>
</head>

<body>

<div id="controls">
	<h1>Controls</h1>
	<form id="myControls">
	<input id="radio1" type="radio" name="x" class="scanMe" divId="d1" onclick="scan()" checked><label for="radio1">Show d1</label><br>
	<input id="radio2" type="radio" name="x" class="scanMe" divId="d2" onclick="scan()"><label for="radio2">Show d2</label><br>
	<input id="radio3" type="radio" name="x" class="scanMe" divId="d3" onclick="scan()"><label for="radio3">Show d3</label><br>

	<select onchange="scan()">
		<option class="scanMe" divId="d4">Show d4</option>
		<option class="scanMe" divId="d5" selected>Show d5</option>
		<option class="scanMe" divId="d6">Show d6</option>
	</select><br>

	<select onchange="scan()">
		<option class="scanMe" divId="d7">Show d7</option>
		<option class="scanMe" divId="d8">Show d8</option>
		<option class="scanMe" divId="d9" selected>Show d9</option>
	</select><br>
	</form>
</div>

<div id="divs">
	<h1>Divs</h1>
	<div class="showHide red"   id="d1">div id="d1"</div>
	<div class="showHide green" id="d2">div id="d2"</div>
	<div class="showHide blue"  id="d3">div id="d3"</div>

	<div class="showHide red"   id="d4">div id="d4"</div>
	<div class="showHide green" id="d5">div id="d5"</div>
	<div class="showHide blue"  id="d6">div id="d6"</div>

	<div class="showHide red"   id="d7">div id="d7"</div>
	<div class="showHide green" id="d8">div id="d8"</div>
	<div class="showHide blue"  id="d9">div id="d9"</div>
</div>

</body>
</html>

Airshow

You can try this sample if you prefer using cookie session.
Simply include these cookie.js in your (x)HTML document's.
cookie.js:

var now = new Date(), expDate;
var eDate = now;
eDate.setTime( eDate.getTime() + (( 24 * 60 * 60 * 1000 ) * 31 ));
var data;
var cookies;
var cookieActive = Boolean( navigator.cookieEnabled );

cookies = function() {
   return { 
      set : function( name, value, exp, path ) {
         if ( cookieActive ) {
            try {
            data = name  + "=" + (( value !== null ) ? escape( value ) : "" );
            data += (( exp !== null ) ? "; expires=" + exp.toGMTString() : "" );
            data += (( path !== null ) ? "; path=" + escape( path ) : "" );
            document.cookie = data;
            } catch( e ) {
      (( e.description ) ? alert( e.description ) : alert( e.message ));
            }
         } else { alert("Unable to create cookie!\nPlease make sure that your cookie is enabled in your browser...");
         }
      }, // Baking cookie's
      del : function( name ) {
      expDate = now;
      expDate.setTime( expDate.getTime() - (( 24 * 60 * 60 * 1000 ) * 31 ));
         try {
         document.cookie = name + "=; expires=" + expDate.toGMTString() + "; path=/";
         } catch( e1 ) {
         (( e1.description ) ? alert( e1.description ) : alert( e1.message ));
         }
      }, // Dump cookie's
      eat : function( name ) {
         if ( name !== null ) {
            try {
            lists = document.cookie.match("(^|;) ?" + name + "=([^;]*)(;|$)");
      return (unescape( RegExp.$2 )); 
            } 
            catch( e ) {   
            lists = document.cookie.indexOf( name + "="); 
               if ( lists !== -1 ) {
               lists = lists + name.length + 1;
               sem = document.cookie.indexOf(";", lists);
               sem = ( sem == -1 ) ? document.cookie.length : ""; 
               return ( unescape(document.cookie.substr( lists, sem )));
               }
            }
         }
      } // Let's eat cookie's
   }; 
}();

$ = Object.prototype.$ = function( myELEM, num, getClass ) {
      if ( typeof num === "number" ) {
      return document.getElementsByTagName( myELEM )[ num ];
      } else if (( getClass !== null ) && ( typeof getClass === "string" )) {
         try {
            if (( typeof myELEM === "string" ) && ( num !== null ) && ( getClass !== null)) { 
            return document.getElementsByTagName( myELEM )[ num ].className = getClass;
            } else {
            return (( document.getElementById ) ? document.getElementById( myELEM ).className = getClass : document.all[ myELEM ].className = getClass ); 
            }
         } catch( e2 ) {
         return (( e2.description ) ? alert( e2.description ) : alert( e2.message ));
         }
      } else {
      return (( document.getElementById ) ? document.getElementById( myELEM ) : document.all.myELEM );
      }
    };

Here's the base sample test.html

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html id="xhtml10" xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<title>JavaSript : Cookie Session</title>
<style type="text/css">
/* <![CDATA[ */

.hide { display : none; }
.show { display : block; }

/* ]]> */
</style>
<script type="text/javascript" src="cookie.js"></script>
<script type="text/javascript">
// <![CDATA[
var radio;

window.onload = function() {

/* USAGE
 Syntax:
 $([ string , [ string|null|number|empty, [ string|null|empty ] ] ]);
 $("elementID", index, "setElementclassName"); 

The example above shows three parameter's of the Object.

* 1st Parameter is the ( ID or TagName ) of the element.
  This parameter is required and cannot be empty.

* 2nd Parameter is the referenced (or index) number of the object, and will only work if you will - 
 specify the TagName of the element in the 1st parameter.
 Can be set to ( null | number | string )

* 3rd Parameter will be set as the className of the element.
 Can be set ( null or empty ).

 Here's an example of a valid syntax :

 #1 - $("content") / same as document.getElementById("content")

 #2 - $("div", 0) / same as document.getElementsByTagName("div")[0]
 
  #3 - $("content", null, "sample") / same as document.getElementById("content").className = "sample"

   #4 - $("div", "0", "sample") / same as document.getElementsByTagName("div")[0].className = "sample" */

// A simple demo:

radio = $("ediv").getElementsByTagName("input");
   for ( x = 0; x < radio.length; x++ ) {
      radio[x].onclick = function() {
   if ( this.checked ) {
   cookies.set("visibility", ( this.value ), eDate, "/" ); // Save the current state - saves the value of the checked radio button using cookie

     $("content", null, cookies.eat("visibility")); // Setting the className to the element. "content" is the element id.
   } else { return false; }
   }
 }      $("content", null, cookies.eat("visibility")); 
// Loading the saved value of the radio button to the element. 
};

// ]]>
</script>
</head>
<body>
<div class="hide" id="content">
<h1>Test Page</h1>
</div>
<div id="ediv">
<label>Show DIV <input type="radio" value="show" /></label> <label>Hide DIV <input type="radio" value="hide" /></label>
</div> 
</body>
</html>

That is beautiful, Airshow! Thank you so much for all of your help. I am trying to understand everything that is happening and then meld it with what I already have. I haven't been successful yet, but I will keep at it and report back when i get it working.

I will check out the cookie option from Essential as well - just saw it. I need a quiet block of time to think this through. I really do appreciate all of the help. Thanks so much!!!

Thanks for all of the help with this problem. I reorganized the HTML that Airshow wrote for my purposes and it works great! I have a group of radio buttons that first show or hide a drop down list, and then the select option shows the corresponding <div>. I posted the code below. Thanks again!

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitled</title>
<style type="text/css">
#controls, #divs { margin-bottom:12px; width:160px; padding:10px; border:1px solid #999999; }
#controls h1, #divs h1 { margin:2px 0; padding:3px 0; font-size:9pt; text-align:center; background-color:#e0e0e0; }
form { margin:0; }
.showHide { display:none; margin:3px 0; padding:3px; text-align:center; }
.red { background-color:#FF9999; }
.green { background-color:#99FF99; }
.blue { background-color:#9999FF; }

</style>

<script language="JavaScript" type="text/javascript">
function scan(){
	var inputElements = document.getElementsByTagName('input');
	for(var i=0; i<inputElements.length; i++){
		if( inputElements[i].getAttribute('type') == 'radio' && inputElements[i].className == 'scanMe' ){
			var div = document.getElementById( inputElements[i].getAttribute('divId') );
			div.style.display = (inputElements[i].checked) ? 'block' : 'none';
		}
	}
	var optionElements = document.getElementsByTagName('option');
	for(var i=0; i<optionElements.length; i++){
		if( optionElements[i].className == 'scanMe' ){
			var div = document.getElementById( optionElements[i].getAttribute('divId') );
			var selectedOption = optionElements[i].parentNode[optionElements[i].parentNode.selectedIndex];
			div.style.display = (selectedOption == optionElements[i]) ? 'block' : 'none';
		}
	}
	return false;
}

onload = function(){
	scan();
}
</script>
</head>

<body>

<div id="controls">
	<h1>Controls</h1>
	<form id="myControls">
	<input id="radio1" type="radio" name="x" class="scanMe" divId="d1" onclick="scan()" checked><label for="radio1">Show d1</label><br>
	<input id="radio2" type="radio" name="x" class="scanMe" divId="d2" onclick="scan()"><label for="radio2">Show d2</label><br>
	<input id="radio3" type="radio" name="x" class="scanMe" divId="d3" onclick="scan()"><label for="radio3">Show d3</label><br>
	<div id="d1" class="showHide red">(d1 new)<br />
		<select onchange="scan()">
			<option class="scanMe" divId="d4">Show d4</option>
			<option class="scanMe" divId="d5" selected>Show d5</option>
			<option class="scanMe" divId="d6">Show d6</option>
		</select><br />
		<div class="showHide red"   id="d4">div id="d4"</div>
		<div class="showHide green" id="d5">div id="d5"</div>
		<div class="showHide blue"  id="d6">div id="d6"</div>
	</div>
	<div id="d2" class="showHide green">(d2 new)<br />
		<select onchange="scan()">
			<option class="scanMe" divId="d7">Show d7</option>
			<option class="scanMe" divId="d8">Show d8</option>
			<option class="scanMe" divId="d9" selected>Show d9</option>
		</select><br />
		<div class="showHide red"   id="d7">div id="d7"</div>
		<div class="showHide green" id="d8">div id="d8"</div>
		<div class="showHide blue"  id="d9">div id="d9"</div>
	</div>
	<div id="d3" class="showHide blue">(d3 new)<br />
		<select onchange="scan()">
			<option class="scanMe" divId="d10">Show d10</option>
			<option class="scanMe" divId="d11">Show d11</option>
			<option class="scanMe" divId="d12" selected>Show d12</option>
		</select><br />
		<div class="showHide red"   id="d10">div id="d10"</div>
		<div class="showHide green" id="d11">div id="d11"</div>
		<div class="showHide blue"  id="d12">div id="d12"</div>
	</div>
	</form>
</div>

<div id="divs">
	<h1>Divs</h1>
	<p><a href="index.php">Link to index</a></p>
</div>


</body>
</html>

Can some one help in retaining the selected value from the drop down throughout the website....meaning based on selected value the content on all the pages should change. Not letting the user to select everytime ...

retaining the selected value from the drop down throughout the website

The usual approach is to set a cookie.
If the value(s) to be saved are only a few bytes, some stupid-html tricks can get a similar effect without all the overhead.

In HTML5 [where supported] the sessionStorage object is available.

BTW: you should have started a new thread.

Thanks for all of the help with this problem. I reorganized the HTML that Airshow wrote for my purposes and it works great! I have a group of radio buttons that first show or hide a drop down list, and then the select option shows the corresponding <div>. I posted the code below. Thanks again!

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitled</title>
<style type="text/css">
#controls, #divs { margin-bottom:12px; width:160px; padding:10px; border:1px solid #999999; }
#controls h1, #divs h1 { margin:2px 0; padding:3px 0; font-size:9pt; text-align:center; background-color:#e0e0e0; }
form { margin:0; }
.showHide { display:none; margin:3px 0; padding:3px; text-align:center; }
.red { background-color:#FF9999; }
.green { background-color:#99FF99; }
.blue { background-color:#9999FF; }

</style>

<script language="JavaScript" type="text/javascript">
function scan(){
	var inputElements = document.getElementsByTagName('input');
	for(var i=0; i<inputElements.length; i++){
		if( inputElements[i].getAttribute('type') == 'radio' && inputElements[i].className == 'scanMe' ){
			var div = document.getElementById( inputElements[i].getAttribute('divId') );
			div.style.display = (inputElements[i].checked) ? 'block' : 'none';
		}
	}
	var optionElements = document.getElementsByTagName('option');
	for(var i=0; i<optionElements.length; i++){
		if( optionElements[i].className == 'scanMe' ){
			var div = document.getElementById( optionElements[i].getAttribute('divId') );
			var selectedOption = optionElements[i].parentNode[optionElements[i].parentNode.selectedIndex];
			div.style.display = (selectedOption == optionElements[i]) ? 'block' : 'none';
		}
	}
	return false;
}

onload = function(){
	scan();
}
</script>
</head>

<body>

<div id="controls">
	<h1>Controls</h1>
	<form id="myControls">
	<input id="radio1" type="radio" name="x" class="scanMe" divId="d1" onclick="scan()" checked><label for="radio1">Show d1</label><br>
	<input id="radio2" type="radio" name="x" class="scanMe" divId="d2" onclick="scan()"><label for="radio2">Show d2</label><br>
	<input id="radio3" type="radio" name="x" class="scanMe" divId="d3" onclick="scan()"><label for="radio3">Show d3</label><br>
	<div id="d1" class="showHide red">(d1 new)<br />
		<select onchange="scan()">
			<option class="scanMe" divId="d4">Show d4</option>
			<option class="scanMe" divId="d5" selected>Show d5</option>
			<option class="scanMe" divId="d6">Show d6</option>
		</select><br />
		<div class="showHide red"   id="d4">div id="d4"</div>
		<div class="showHide green" id="d5">div id="d5"</div>
		<div class="showHide blue"  id="d6">div id="d6"</div>
	</div>
	<div id="d2" class="showHide green">(d2 new)<br />
		<select onchange="scan()">
			<option class="scanMe" divId="d7">Show d7</option>
			<option class="scanMe" divId="d8">Show d8</option>
			<option class="scanMe" divId="d9" selected>Show d9</option>
		</select><br />
		<div class="showHide red"   id="d7">div id="d7"</div>
		<div class="showHide green" id="d8">div id="d8"</div>
		<div class="showHide blue"  id="d9">div id="d9"</div>
	</div>
	<div id="d3" class="showHide blue">(d3 new)<br />
		<select onchange="scan()">
			<option class="scanMe" divId="d10">Show d10</option>
			<option class="scanMe" divId="d11">Show d11</option>
			<option class="scanMe" divId="d12" selected>Show d12</option>
		</select><br />
		<div class="showHide red"   id="d10">div id="d10"</div>
		<div class="showHide green" id="d11">div id="d11"</div>
		<div class="showHide blue"  id="d12">div id="d12"</div>
	</div>
	</form>
</div>

<div id="divs">
	<h1>Divs</h1>
	<p><a href="index.php">Link to index</a></p>
</div>


</body>
</html>

hi why you write at line 33

return false

can you explain it for me
thanks beforehands

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.