Solved

Update Hidden form field using javascript

Posted on 2011-03-10
6
474 Views
Last Modified: 2012-06-21
How do I update hidden fields in a form. I have the following html code near the top of the BODY:
<div style="margin-left: 25px; padding-top: 10px;">
			<form action="<?php echo $arch_config['portfolio_url'] . "print_html.php" ?>" method="GET" name="hidden_form">
    		<input type="hidden" name="order" id="hidden_order" value='Alphabetical' />
    		<input type="hidden" name="filters[state]" id="hidden_state" value="" />
    		<input type="hidden" name="filters[county]" id="hidden_county" value="" />
    		<input type="hidden" name="filters[city]" id="hidden_city" value="" />
    		<input type="hidden" name="filters[denomination]" id="hidden_denomination" value="" />
    		<input type="hidden" name="filters[service]" id="hidden_service" value="" />
    		<input type="hidden" name="filters[has_images]" id=hidden_has_images value="" />
				<input type="submit" value="Print Page" class="submit" target="_blank" />
			</form>
		</div>

.
.
.
Near the bottom of the BODY area I have this code:

document.getElementById("hidden_order").value = "0";
document.getElementById("hidden_state").value = "New Jersey";
document.getElementById("hidden_county").value = "";
document.getElementById("hidden_city").value = "";
document.getElementById("hidden_denomination").value = "Baptist";
document.getElementById("hidden_service").value = "";
document.getElementById("hidden_has_images").value = "";


In between these two pieces of code, there is javascript that is updating other form elements during the page load. I am wanting to put the results of this 'middle' code into the form hidden fields located at the top of the page.

What am I doing wrong?

Open in new window

0
Comment
Question by:dnotestine
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
6 Comments
 
LVL 4

Expert Comment

by:GeoffHarper
ID: 35100796
Can you post the whole file?  I don't see anything wrong with the excerpts you posted.
0
 

Author Comment

by:dnotestine
ID: 35101178
It wouldn't allow me to post the page so it is included as an attachment
<?php
	global $title;
	$title = "Portfolio";

	// Read current limit
	$limit = clean_input_by_array( $_GET['limit'], array( 10, 25, 50 ), 25 );

	// Read current page
	$page = clean_input_as_integer( $_GET['page'], 1 );


	$filters = clean_input_as_string_by_hash( $_GET['filters'], array( 'service', 'state', 'county','city', 'has_images', 'denomination' ) );

	$order = clean_input_as_string_by_array( $_GET['order'], array( 'name', 'city', 'state', 'year' ) );
	$order_string = implode( ',', $order);
	
	if( $order[ count($order) - 1 ] != 'name' ) $order[] = 'name';


	// $churches = get_churches( $limit, $page, $order,  $filters );
	
	$locations = get_states_cities_and_counties();
	$locations_json = json_encode($locations);
	
	$denominations = get_denominations();
	
	$services = get_amenities();

	?>
		<script type="text/javascript" charset="utf-8">
			var locations_obj = <?php echo $locations_json ?>;
			var locations = [];
			for(var loc in locations_obj){
				locations.push(locations_obj[loc]);
			};
		</script>
		<h1 id='port-title'>Portfolio &amp; Installation List</h1>
		
		<form id="filter-sort-block" action="<?php echo $arch_config['portfolio_url'] ?>" method="get" class="no_js">
			<fieldset id="sort">
				<h2>Sort</h2>
				<select name="order" id='sort-order'>
					<?php select_option('name','Alphabetical', $order_string) ?>
				</select>
				<input type="submit" value="Sort" class="submit" />
				<div id="ajax-loading">
					<img src='<?php echo $arch_config['portfolio_url'] ?>images/ajax-indicator-dk.gif' width="31" height="31" />
				</div>
			</fieldset>
			<fieldset id="filter">
				<h2>Filter</h2>
				<div id="filter-one" class="column">
					<label id="state_filter">
						<strong>State</strong>
						<select name="filters[state]" id='church_state'>
							<option value=""></option>
							<?php $selected_state = ""; ?>
							<?php foreach($locations as $location) : ?>
								<?php $selected_state = select_option($location['name'], $location['name'], $filters['state']) ?>
								<?php if ($selected_state != ""){$selected_state_final = $selected_state;}
								?>
							<?php endforeach; ?>
						</select>
					</label>
					<label id="county_filter" class="disabled">
						<strong>County</strong>
						<select name="filters[county]" id="church_state_counties" disabled="disabled">
							<option selected="selected"></option>
						</select>
					</label>
					<label id="city_filter" class="disabled">
						<strong>City</strong>
						<select name="filters[city]" id="church_state_cities" disabled="disabled">
							<option selected="selected"></option>
						</select>
					</label>
				</div>
				<div id="filter-two" class="column">
					<label id="denomination_filter">
						<strong>Denomination</strong>
						<select name="filters[denomination]" id="church_denomination">
							<?php foreach($denominations as $denomination) : ?>
								<?php select_option($denomination, $denomination, $filters['denomination']) ?>
							<?php endforeach; ?>
						</select>
					</label>
					<label id="services_filter"><strong>Services</strong>
						<select name="filters[service]" id="church_amenities">
							<option value=""></option>
							<?php foreach($services as $service) : ?>
								<?php select_option($service->id, $service->name, $filters['service']) ?>
							<?php endforeach; ?>
						</select>
					</label>
					<label id="images_filter">
						<strong>Photos</strong>
						<select name="filters[has_images]" id="church_photos">
							<option value=""></option>
							<?php select_option('1','Only With Photos', $filters['has_images']) ?>
						</select>
					</label>
				</div>
					
				<div class="action_row">
					<input type="submit" value="Filter" class="submit"  />
				</div>
			</fieldset>
		</form>
		

		<div style="margin-left: 25px; padding-top: 10px;">
			<form action="<?php echo $arch_config['portfolio_url'] . "print_html.php" ?>" method="GET" name="hidden_form">
    		<input type="hidden" name="order" id="hidden_order" value='Alphabetical' />
    		<input type="hidden" name="filters[state]" id="hidden_state" value="" />
    		<input type="hidden" name="filters[county]" id="hidden_county" value="" />
    		<input type="hidden" name="filters[city]" id="hidden_city" value="" />
    		<input type="hidden" name="filters[denomination]" id="hidden_denomination" value="" />
    		<input type="hidden" name="filters[service]" id="hidden_service" value="" />
    		<input type="hidden" name="filters[has_images]" id=hidden_has_images value="" />
				<input type="submit" value="Print Page" class="submit" target="_blank" />
			</form>
		</div>

		<!-- 
<input type="button" value="Print" onClick="request_print(page, true);">
		 -->
		 
		<!-- <form name="myform" action="">
<input type="button" value="Print" onClick="request_print(page, true);">
			<a href="javascript: request_print(page, true);">Print</a>
		</form> -->
		
	<?php

	//get_churches_paging( $limit, $page, $filters );
	
	$pagerLayout = new Doctrine_Pager_Layout(
	      new Doctrine_Pager(
	            get_churches_query($order, $filters),
	            $page,
	            $limit
	      ),
	      new Doctrine_Pager_Range_Sliding(array(
	            'chunk' => 30
	      )),
	      $arch_config['portfolio_url'] . '?page={%page_number}'
	);
	
	$pagerLayout->setTemplate('<a href="{%url}"><em>{%page}</em></a>');
	$pagerLayout->setSelectedTemplate('<span><em>{%page}</em></span>');
	
	$pager = $pagerLayout->getPager();
	
	$churches = $pager->execute();
	
	
	?>
	<div id="church-portfolio-wrapper">
	<div class="pagination">
		<?php $pagerLayout->display() ?>
	</div>
	<ul id="church-portfolio" class="no_js">
		
	<?php
	foreach($churches as $church):
		include 'includes/_church.php';
	endforeach; 
	?>
	
	</ul>
	<div class="pagination">
		<?php $pagerLayout->display() ?>
	</div>
	</div>
		<span class="clear">&nbsp;</span>
		
		
		
		<!--[if lte IE 7]>
		<link rel="stylesheet" href="<?php echo $arch_config['portfolio_url'] ?>css/ie.css" type="text/css" />
		<![endif]-->
		<!--[if lte IE 6]>
		<link rel="stylesheet" href="<?php echo $arch_config['portfolio_url'] ?>css/ie6.css" type="text/css" />
		<![endif]-->
		<!-- <script type='text/javascript' 
		        src='http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'></script> -->
		        
		<script src="<?php echo $arch_config['portfolio_url'] ?>js/jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script>
		<script src="<?php echo $arch_config['portfolio_url'] ?>js/jquery.history.js" type="text/javascript" charset="utf-8"></script>
		<script src="<?php echo $arch_config['portfolio_url'] ?>js/jquery.scrollTo-min.js" type="text/javascript" charset="utf-8"></script>
		<script src="<?php echo $arch_config['portfolio_url'] ?>js/push-pop.js" type="text/javascript" charset="utf-8"></script>
		
		<script type="text/javascript" charset="utf-8">
			var cache = {};
			var updating_state = false;
			var updating_county = false;
			var history_writing = false;
			$(document).ready(function(){
				
				$("#church-portfolio li").live("click", function(e){
					window.location = $(this).find("a").attr("href");
					e.preventDefault();
				});
				$("#church-portfolio.no_js, #filter-sort-block.no_js").removeClass("no_js");
				
				$("#church_state").change(function(e){
					set_state(this.selectedIndex,false);
				});
				
				$("#church_state_counties").change(function(e){
					if (updating_state) return;
					set_county(this.selectedIndex,false);
				});
				
				$("#church_state_cities").change(function(e){
					if (updating_state || updating_county) return;
					request_update();
				})
				
				
				$.History.bind(function(state){
					if(state != ""){
						reset_from_history(state);	
					} else {
						reset_from_history('o0-s0-c0-y0-d0-a0-i0-p1');
					}	
				});
				
				$("div.pagination:eq(0) a").live("click", function(e){
					e.preventDefault();
					var href = $(this).attr('href');
					var matches = href.match(/page=(\d+)$/);
					if(matches && matches.length == 2){
						request_update(parseInt(matches[1]));
					};
				})
				
				$("div.pagination:eq(1) a").live("click", function(e){
					e.preventDefault();
					var href = $(this).attr('href');
					var matches = href.match(/page=(\d+)$/);
					if(matches && matches.length == 2){
						$(window)._scrollable().scrollTo($("#port-title"), 300, {
							onAfter:function(){
								request_update(parseInt(matches[1]));
							}
						});
					};
				});
				
				
				$("#filter-sort-block")[0].reset();
				$("#filter-sort-block").submit(function(e){
					e.preventDefault();
					request_update();
					return false;
				}).find("select:not(#church_state,#church_state_counties,#church_state_cities)").change(function(e){
					if(history_writing) return;
					request_update();
				});
			});
			
			function build_history_string(page){
				if(!page) page = 1;
				var key = "";
				key += "o" + $("#sort-order")[0].selectedIndex + "-";
				key += "s" + $("#church_state")[0].selectedIndex + "-";
				key += "c" + $("#church_state_counties")[0].selectedIndex + "-";
				key += "y" + $("#church_state_cities")[0].selectedIndex + "-";
				key += "d" + $("#church_denomination")[0].selectedIndex + "-";
				key += "a" + $("#church_amenities")[0].selectedIndex + "-";
				key += "i" + $("#church_photos")[0].selectedIndex + "-";
				key += "p" + page;
				
				return key;
			}
			
			function set_county(index, update, city_id){
				updating_county = true;
				var state_id = $("#church_state")[0].selectedIndex;
				if(!state_id) state_id = 0;
				if(!city_id) city_id = 0;
				
				if(state_id == 0){
					$("#church_state_counties").empty().append("<option></option>")[0].selectedIndex = 0;
					$("#church_state_counties").val('').attr('disabled','disabled').blur();
					$("#county_filter").addClass('disabled');
				} else if (update) {
					state_id = state_id - 1; // Account for the difference in indexes
					var state = locations[state_id]; // Convert index to string
					var counties = state.counties;
					var cnty_str = "";
					if(counties.length > 1){
						cnty_str += "<option></option>";
					};
					for(var i = 0; i<counties.length; i++){
						var county = counties[i];
						cnty_str += '<option value="' + county.name + '">' + county.name + '</option>';
					};
					
					$("#church_state_counties").empty().append(cnty_str)[0].selectedIndex = index;
					$("#church_state_counties").removeAttr('disabled');
					$("#county_filter").removeClass('disabled');
				}
				
				set_city(city_id);
				updating_county = false;
				if(!updating_state) request_update();
			}
			
			function set_city(index){
				
				var state_id = $("#church_state")[0].selectedIndex;
				if(!state_id) state_id = 0;
				
				var county_id = $("#church_state_counties")[0].selectedIndex;
				if(!county_id) county_id = 0;
				
				if(state_id == 0){
					$("#church_state_cities").empty().append("<option></option>")[0].selectedIndex = 0;
					$("#church_state_cities").val('').attr('disabled','disabled').blur();
					$("#city_filter").addClass('disabled');
				} else if ( $("#church_state_counties").val() == ""){
					state_id = state_id - 1;
					var state = locations[state_id]; // Convert index to string
					var cities = state.cities;
					
					var city_str = "";
					
					if(cities.length > 1){
						city_str += "<option></option>";
					};
					
					for(var j = 0; j<cities.length; j++){
						var city = cities[j];
						city_str += '<option value="' + city + '">' + city + '</option>';
					};
					
					$("#church_state_cities").empty().append(city_str)[0].selectedIndex = index;
					$("#church_state_cities").removeAttr('disabled');
					$("#city_filter").removeClass('disabled');
					
				} else {
					// County selected
					state_id = state_id - 1; // Account for the difference in indexes
					var state = locations[state_id]; // Convert index to string
					var counties = state.counties;
					
					if(counties.length > 1) county_id = county_id - 1; // Account for difference in indexes
					
					var county = state.counties[county_id];
					var cities = county.cities;
					var city_str = "";
					
					if(cities.length > 1){
						city_str += "<option></option>";
					};
					
					for(var j = 0; j<cities.length; j++){
						var city = cities[j];
						city_str += '<option value="' + city + '">' + city + '</option>';
					};
					
					$("#church_state_cities").empty().append(city_str)[0].selectedIndex = index;
					$("#church_state_cities").removeAttr('disabled');
					$("#city_filter").removeClass('disabled');
				}
			}
			
			function set_state(index, update, county_id, city_id){
				updating_state = true;
				
				if(update !== false) update = true;
				if(!county_id) county_id = 0;
				if(!city_id) city_id = 0;
				
				index = parseInt(index);
				if(update) $("#church_state")[0].selectedIndex = index;
				
				set_county(county_id, true, city_id);
				
				updating_state = false;
				if(!history_writing) request_update();
			}
			
			function reset_from_history(key){
				history_writing = true;
				var matches = key.match(/^o(\d+)-s(\d+)-c(\d+)-y(\d+)-d(\d+)-a(\d+)-i(\d+)-p(\d+)$/);
				if(!matches) return;
				
				
				$("#sort-order")[0].selectedIndex			= parseInt(matches[1]);
				set_state(parseInt(matches[2]),true,parseInt(matches[3]),parseInt(matches[4]));
				$("#church_denomination")[0].selectedIndex  = parseInt(matches[5]); 
				$("#church_amenities")[0].selectedIndex		= parseInt(matches[6]);
				$("#church_photos")[0].selectedIndex		= parseInt(matches[7]);
				
				var page = parseInt(matches[8]);
				
				history_writing = false;
				
				
				
				request_update(page, false);
			}
			
			function request_update(page, set_history){

				if(!page) page = 1;	

				if(set_history !== false) set_history = true;

				var history_string = build_history_string(page);
				$(document.body).addClass("loading");
				if(set_history){
					$.History.setHash(history_string);
				} else {
					if(cache[history_string]){
						$("#church-portfolio-wrapper").replaceWith(cache[history_string]);
						$(document.body).removeClass("loading");
					} else {
						$.get('<?php echo $arch_config['portfolio_url'] ?>portfolio-browse.ajax.php?' + $("#filter-sort-block").serialize(),
							{page:page},
							function(data){
								cache[history_string] = data;
								$("#church-portfolio-wrapper").replaceWith(data);
								$(document.body).removeClass("loading");
							}
						);	
					}
				}
				
document.getElementById("hidden_order").value = "0";
document.getElementById("hidden_state").value = "New Jersey";
document.getElementById("hidden_county").value = "";
document.getElementById("hidden_city").value = "";
document.getElementById("hidden_denomination").value = "Baptist";
document.getElementById("hidden_service").value = "";
document.getElementById("hidden_has_images").value = "";

				
				
				
				
			}
			
		
		</script>
	<?php


?>

Open in new window

0
 
LVL 4

Accepted Solution

by:
GeoffHarper earned 500 total points
ID: 35101341
Those last few lines:

-------------------------------

);      
                              }
                        }
                        
document.getElementById("hidden_order").value = "0";
document.getElementById("hidden_state").value = "New Jersey";
document.getElementById("hidden_county").value = "";
document.getElementById("hidden_city").value = "";
document.getElementById("hidden_denomination").value = "Baptist";
document.getElementById("hidden_service").value = "";
document.getElementById("hidden_has_images").value = "";
                  }

-------------------------------

Delete that extraneous ");" - it's probably causing a JavaScript error.
Then move the closing bracket below the "document." lines to above the "document." lines,
so you end up with this:

-------------------------------
                              }
                        }
                        
                  }

document.getElementById("hidden_order").value = "0";
document.getElementById("hidden_state").value = "New Jersey";
document.getElementById("hidden_county").value = "";
document.getElementById("hidden_city").value = "";
document.getElementById("hidden_denomination").value = "Baptist";
document.getElementById("hidden_service").value = "";
document.getElementById("hidden_has_images").value = "";

-------------------------------


-Geoff
0
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

 

Author Comment

by:dnotestine
ID: 35101531
Thanks, but I don't think that was it. The structure tested OK. I cleaned up, just the function, so you could visualize it better

      function request_update(page, set_history){
            if(!page) page = 1;      
            if(set_history !== false) set_history = true;
            var history_string = build_history_string(page);
            $(document.body).addClass("loading");
            if(set_history){
                  $.History.setHash(history_string);
            } else {
                  if(cache[history_string]){
                        $("#church-portfolio-wrapper").replaceWith(cache[history_string]);
                        $(document.body).removeClass("loading");
                  } else {
                        $.get('<?php echo $arch_config['portfolio_url'] ?>portfolio-browse.ajax.php?' + $("#filter-sort-block").serialize(),
                              {page:page},
                              function(data){
                                    cache[history_string] = data;
                                    $("#church-portfolio-wrapper").replaceWith(data);
                                    $(document.body).removeClass("loading");
                              }
                        );      
                  }
            }
document.getElementById("hidden_order").value = "0";
document.getElementById("hidden_state").value = "New Jersey";
document.getElementById("hidden_county").value = "";
document.getElementById("hidden_city").value = "";
document.getElementById("hidden_denomination").value = "Baptist";
document.getElementById("hidden_service").value = "";
document.getElementById("hidden_has_images").value = "";
      }
0
 
LVL 4

Expert Comment

by:GeoffHarper
ID: 35101554
Did you try it like I said?
0
 

Author Comment

by:dnotestine
ID: 35101654



AHHHHHHHHHHHHHHHHHHHHHH!!!

I'm an ass :-(

It worked perfectly - thanks for your help

Cheers
David
0

Featured Post

How our DevOps Teams Maximize Uptime

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us. Read the use case whitepaper.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
The Windows functions GetTickCount and timeGetTime retrieve the number of milliseconds since the system was started. However, the value is stored in a DWORD, which means that it wraps around to zero every 49.7 days. This article shows how to solve t…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will the learn the benefit of plain text editors and code an HTML5 based template for use in further tutorials.

738 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