Lassie Posted August 23, 2007 Share Posted August 23, 2007 I have developed a form to register a property in a db. The form needs the selection of a country and then based on that selection the selection of regions from the selected country. I have a program which allows selection of a country and then a region but it uses java script which I would like to avoid. I also just wanted one submit button if possible. Does anyone have an idea of how to approach this please? The reristration form is structured thus //Check form submitted and validate POST entries //update db //redirect // Display form //show errors and valid entries for correction //submit form This is the first part of the registration form that I need to make the selection in. <h1>Register Your Timeshare</h1> <form action="reg_property.php" method="post"> <fieldset> <legend>RCI Reference Detail</legend> <p> <label for="rci_ref">RCI Reference:<em class="required">(required - numeric)</em></label> <input type="text" name="rci_ref" size="10" maxlength="10" value="<?php if (isset($_POST['rci_ref'])) echo $_POST['rci_ref']; ?>" /></p> <p> <label for="resort_name">Resort Name:</label> <input type="text" name="resort_name" size="35" maxlength="30" value="<?php if (isset($_POST['resort_name'])) echo $_POST['resort_name']; ?>" /></p> //Need to select country and Region from drop down list <p> <label for="country">Country:</label> <input type="text" name="country" size="35" maxlength="30" value="<?php if (isset($_POST['country'])) echo $_POST['country']; ?>" /></p> <p> <label for="region">Region of Country:</label> <input type="text" name="region" size="35" maxlength="30" value="<?php if (isset($_POST['region'])) echo $_POST['region']; ?>" /></p> </fieldset> The populate program which allows the selection of the country and the regions is as follows: <SCRIPT language=JavaScript> function reload(form) { // Setting the variable with the value of selected country's ID var val=populate.countryList.options[populate.countryList.options.selectedIndex].value; // Sending the country id in the query string to retrieve the city list self.location='populate.php?countryId=' + val ; } </script> <? /* - Function to return the Country list as an array */ function getCountryList() { // Country List array $countryList = array ( '1'=> 'Spain', '2'=> 'France', '3'=> 'United States', ); return $countryList; return $countryList; } /* - Function to return the City list as an array - Country ID is used to generate the city list */ function getCityList($countryId) { // City list array // First key of the array is the Country ID, which holds an array of City list $cityList = array ( '1'=> array ('Almeria', 'Costa del Sol'), '2'=> array ('Midi-Pyrenees', 'Languedoc-Roussillon','Aquitane'), '3'=> array ('Arizona','Florida') ); return $cityList[$countryId]; } ?> <form action="populate.php" name="populate"> <? // Retrieving the country list $countryList = getCountryList(); // Setting the variable if the country is selected for its city list @$countryId = $_GET['countryId']; // Retrieving the city list if a country is selected $cityList = ($countryId) ? getCityList($countryId) : null; if (!empty($countryList)) { // Generating the country drop down menu echo "<select onChange='reload(this.form)' name='countryList'>"; foreach ($countryList as $key => $value) { echo "<option value='$key'"; if ($countryId == $key) echo "selected"; echo ">$value</option>"; } echo "</select>"; } if (!empty($cityList)) { // Generating the city drop down menu if a country is selected echo "<select name='cityList'>"; foreach ($cityList as $key => $value) { echo "<option value='$key'>$value</option>"; } echo "</select>"; } ?> </form> Quote Link to comment https://forums.phpfreaks.com/topic/66366-how-do-i-populate-a-drop-down-list-in-a-form-on-the-basis-of-a-first-selection/ Share on other sites More sharing options...
Psycho Posted August 23, 2007 Share Posted August 23, 2007 This question has been asked and answered many times. If you want to avoid JavaScript then you must have a two step process for the user: 1) select the parent element and submit the page 2) Display the appropriate child elements. In my opinion that is a tedious solution for the end user. Javascript is the only way to change the child list interactively. With Javascript you have two options. 1) Load all parent/child lists into Javascript arrays and do all the work on the client-side or 2) Use an onchange event on the parent element to call an AJAX process (javascript + PHP) which will call a PHP process to return back to the page the updated child list. Quote Link to comment https://forums.phpfreaks.com/topic/66366-how-do-i-populate-a-drop-down-list-in-a-form-on-the-basis-of-a-first-selection/#findComment-332076 Share on other sites More sharing options...
Lassie Posted August 23, 2007 Author Share Posted August 23, 2007 Thanks for that. I will think it through. Quote Link to comment https://forums.phpfreaks.com/topic/66366-how-do-i-populate-a-drop-down-list-in-a-form-on-the-basis-of-a-first-selection/#findComment-332088 Share on other sites More sharing options...
Lassie Posted August 23, 2007 Author Share Posted August 23, 2007 I have gone for the java option but I am not sure how to capture the 2 values, country and region in the code I have. If I submit the form to same page and I want to validate the 2 values and then show the rest of the form. Here is the code <SCRIPT language=JavaScript> function reload(form) { // Setting the variable with the value of selected country's ID var val=populate.countryList.options[populate.countryList.options.selectedIndex].value; // Sending the country id in the query string to retrieve the city list self.location='drop.php?countryId=' + val ; } </script> <? /* - Function to return the Country list as an array */ function getCountryList() { // Country List array $countryList = array ( '1'=> 'Spain', '2'=> 'France', '3'=> 'United States', ); return $countryList; return $countryList; } /* - Function to return the City list as an array - Country ID is used to generate the city list */ function getCityList($countryId) { // City list array // First key of the array is the Country ID, which holds an array of City list $cityList = array ( '1'=> array ('Almeria', 'Costa del Sol'), '2'=> array ('Midi-Pyrenees', 'Languedoc-Roussillon','Aquitane'), '3'=> array ('Arizona','Florida') ); return $cityList[$countryId]; } ?> <form action="drop.php" name="populate"> <fieldset> <legend>Enter Country</legend> <p> <label for="country">Country:</label> <? // Retrieving the country list $countryList = getCountryList(); // Setting the variable if the country is selected for its city list @$countryId = $_GET['countryId']; // Retrieving the city list if a country is selected $cityList = ($countryId) ? getCityList($countryId) : null; if (!empty($countryList)) { // Generating the country drop down menu echo "<select onChange='reload(this.form)' name='countryList'>"; foreach ($countryList as $key => $value) { echo "<option value='$key'"; if ($countryId == $key) echo "selected"; echo ">$value</option>"; } echo "</select>"; } if (!empty($cityList)) { // Generating the city drop down menu if a country is selected echo "<select name='cityList'>"; foreach ($cityList as $key => $value) { echo "<option value='$key'>$value</option>"; } echo "</select>\n"; } ?> //need to capture both values. </p> <div align="center"><input type="submit" name="submit" value="submit" /></div> <input type="hidden" name="submitted" value="TRUE" /> </fieldset> </form> Quote Link to comment https://forums.phpfreaks.com/topic/66366-how-do-i-populate-a-drop-down-list-in-a-form-on-the-basis-of-a-first-selection/#findComment-332128 Share on other sites More sharing options...
Psycho Posted August 23, 2007 Share Posted August 23, 2007 Well, I assume you mean Javascript (Java is something entirely different). If you are going to use Javascript then you do not need to submit the form to itself. If you don't have a huge list of countries and regions, just do it all in the javascript. If you have many, many countries and regions then you would want to incorporate AJAX. here is an example of a Javascript only solution: <html> <head> <script type="text/javascript"> // State lists var states = new Array(); states['Canada'] = new Array('Alberta','British Columbia','Ontario'); states['Mexico'] = new Array('Baja California','Chihuahua','Jalisco'); states['United States'] = new Array('California','Florida','New York'); // City lists var cities = new Array(); cities['Canada'] = new Array(); cities['Canada']['Alberta'] = new Array('Edmonton','Calgary'); cities['Canada']['British Columbia'] = new Array('Victoria','Vancouver'); cities['Canada']['Ontario'] = new Array('Toronto','Hamilton'); cities['Mexico'] = new Array(); cities['Mexico']['Baja California'] = new Array('Tijauna','Mexicali'); cities['Mexico']['Chihuahua'] = new Array('Ciudad Juárez','Chihuahua'); cities['Mexico']['Jalisco'] = new Array('Guadalajara','Chapala'); cities['United States'] = new Array(); cities['United States']['California'] = new Array('Los Angeles','San Francisco'); cities['United States']['Florida'] = new Array('Miami','Orlando'); cities['United States']['New York'] = new Array('Buffalo','New York'); function setStates(){ cntrySel = document.getElementById('country'); stateSel = document.getElementById('state'); stateList = states[cntrySel.value]; changeSelect(stateSel, stateList); setCities(); } function setCities(){ cntrySel = document.getElementById('country'); stateSel = document.getElementById('state'); citySel = document.getElementById('city'); cityList = cities[cntrySel.value][stateSel.value]; changeSelect(citySel, cityList); } //**************************************************************************// // FUNCTION changeSelect(fieldObj, valuesAry, [optTextAry], [selectedVal]) // //**************************************************************************// function changeSelect(fieldObj, valuesAry, optTextAry, selectedValue) { //Clear the select list fieldObj.options.length = 0; //Set the option text to the values if not passed optTextAry = (optTextAry)?optTextAry:valuesAry; //Itterate through the list and create the options for (i in valuesAry) { selectFlag = (selectedValue && selectedValue==valuesAry[i])?true:false; fieldObj.options[fieldObj.length] = new Option(optTextAry[i], valuesAry[i], false, selectFlag); } } </script> </head> <body onload="setStates();"> <form name="test" method="POST" action="processingpage.php"> Country: <select name="country" id="country" onchange="setStates();"> <option value="Canada">Canada</option> <option value="Mexico">Mexico</option> <option value="United States">United States</option> </select> <br> State: <select name="state" id="state" onchange="setCities();"> <option value="">Please select a Country</option> </select> <br> City: <select name="city" id="city" onchange="alert(this.options[this.selectedIndex].value)"> <option value="">Please select a Country</option> </select> </form> </body> </html> Quote Link to comment https://forums.phpfreaks.com/topic/66366-how-do-i-populate-a-drop-down-list-in-a-form-on-the-basis-of-a-first-selection/#findComment-332171 Share on other sites More sharing options...
Lassie Posted August 23, 2007 Author Share Posted August 23, 2007 Yes,sorry I did mean javascript although i am not familiar with it. Thank you for the example I will try and get to grips with it. My initial question is how are values passed in this way? As with Post and Get? The form also indicates selecting country value twice when I would have expected state/city in the example. I will investigate. Thanks again Quote Link to comment https://forums.phpfreaks.com/topic/66366-how-do-i-populate-a-drop-down-list-in-a-form-on-the-basis-of-a-first-selection/#findComment-332400 Share on other sites More sharing options...
Psycho Posted August 24, 2007 Share Posted August 24, 2007 Well, I'm not quite understanding your questions. The values are passed when you submit the form in whatever way you want POST or GET. Depends on the method you set for the form. Using the above scenario when the page loads you would get your list of countries and regions and create the javascript arrays for the page. Where is the country value selected twice? Not sure what you mean unless you are referring to the fact that the default values for State and City first say "Select a Country", but if you have javascript enabled you would never see that. That example I posted uses three separate levels of values (Countries, States (aka Regions), and cities). Each one is dependant upon the other. In your situation you would only need two fields: country & region. Here's an exampe using your form and data: <html> <head> <script type="text/javascript"> // Region lists var regions = new Array(); regions['Spain'] = new Array('Almeria', 'Costa del Sol'); regions['France'] = new Array('Midi-Pyrenees', 'Languedoc-Roussillon','Aquitane'); regions['United States'] = new Array('Arizona','Florida'); function setRegions(){ cntrySel = document.getElementById('country'); regionSel = document.getElementById('region'); regionList = regions[cntrySel.value]; changeSelect(regionSel, regionList); } //**************************************************************************// // FUNCTION changeSelect(fieldObj, valuesAry, [optTextAry], [selectedVal]) // //**************************************************************************// function changeSelect(fieldObj, valuesAry, optTextAry, selectedValue) { //Clear the select list fieldObj.options.length = 0; //Set the option text to the values if not passed optTextAry = (optTextAry)?optTextAry:valuesAry; //Itterate through the list and create the options for (i in valuesAry) { selectFlag = (selectedValue && selectedValue==valuesAry[i])?true:false; fieldObj.options[fieldObj.length] = new Option(optTextAry[i], valuesAry[i], false, selectFlag); } } </script> </head> <body onload="setRegions();"> <h1>Register Your Timeshare</h1> <form action="reg_property.php" method="post"> <fieldset> <legend>RCI Reference Detail</legend> <p> <label for="rci_ref">RCI Reference:<em class="required">(required - numeric)</em></label> <input type="text" name="rci_ref" size="10" maxlength="10" value="<?php if (isset($_POST['rci_ref'])) echo $_POST['rci_ref']; ?>" /></p> <p> <label for="resort_name">Resort Name:</label> <input type="text" name="resort_name" size="35" maxlength="30" value="<?php if (isset($_POST['resort_name'])) echo $_POST['resort_name']; ?>" /></p> //Need to select country and Region from drop down list <p> <label for="country">Country:</label> <select name="country" id="country" onchange="setRegions();"> <option value="Spain"<?php if ($_POST['country']=='Spain') echo ' selected'; ?>>Spain</option> <option value="France"<?php if ($_POST['country']=='>France') echo ' selected'; ?>>France</option> <option value="United States"<?php if ($_POST['country']=='United States') echo ' selected'; ?>>United States</option> </select> <p> <label for="region">Region of Country:</label> <select name="region" id="region"></select> </fieldset> </form> </body> </html> Quote Link to comment https://forums.phpfreaks.com/topic/66366-how-do-i-populate-a-drop-down-list-in-a-form-on-the-basis-of-a-first-selection/#findComment-332760 Share on other sites More sharing options...
Lassie Posted August 24, 2007 Author Share Posted August 24, 2007 Thanks for coming back. I will study this to properly follow it. Quote Link to comment https://forums.phpfreaks.com/topic/66366-how-do-i-populate-a-drop-down-list-in-a-form-on-the-basis-of-a-first-selection/#findComment-332849 Share on other sites More sharing options...
Lassie Posted August 24, 2007 Author Share Posted August 24, 2007 hi mjdamato, I have incorporated the js example but I get an error 'undefined index country' Does the example store the country selection as post data as well as the region? I need both country and region in the post data. Sorry to bother you but I dont know js and I cant quite understand the effect of this line of code: <select name="country" id="country" onchange="setRegions();"> Any advice appreciated. Quote Link to comment https://forums.phpfreaks.com/topic/66366-how-do-i-populate-a-drop-down-list-in-a-form-on-the-basis-of-a-first-selection/#findComment-332918 Share on other sites More sharing options...
Psycho Posted August 24, 2007 Share Posted August 24, 2007 I am not getting the error you describe. Please provide the HTML output of the country/region fields and the javascript code. As stated previously, the javascript has nothing to do with whether the data is sent via POST or GET. You have a form and the data will be sent however it would normally be sent according to how you set up the form. The form contains the country field and the region field so the values of those two fields will be sent when the form is submitted. All js is doing is adding some interactivity to the form. Quote Link to comment https://forums.phpfreaks.com/topic/66366-how-do-i-populate-a-drop-down-list-in-a-form-on-the-basis-of-a-first-selection/#findComment-333038 Share on other sites More sharing options...
Lassie Posted August 24, 2007 Author Share Posted August 24, 2007 I follow what you are saying but cant spot the problem. I have provided below the code. I am afraid its rather full, but its the complete job. I put the js in my header and added the rest to my main form and validation. The error is:- An error occurred.........\js.php on line 320: Undefined index:country Date/Time..>Spain Repeated for 321 >France and >322 United States. The header is: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml2/DTD/xhtml1-strict. dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Timeshare1</title> <style type="text/css" media="screen">@import "./includes/layout.css";</style> <style type="text/css" media="screen">@import "./includes/full.css";</style> <!--[if lte IE 6] <style type="text/css" media="screen">@import "./includes/flyout_ie.css";</style> <![endif]--> </head> <script type="text/javascript"> // Region lists var regions = new Array(); regions['Spain'] = new Array('Almeria', 'Costa del Sol'); regions['France'] = new Array('Midi-Pyrenees', 'Languedoc-Roussillon','Aquitane'); regions['United States'] = new Array('Arizona','Florida'); function setRegions(){ cntrySel = document.getElementById('country'); regionSel = document.getElementById('region'); regionList = regions[cntrySel.value]; changeSelect(regionSel, regionList); } //**************************************************************************// // FUNCTION changeSelect(fieldObj, valuesAry, [optTextAry], [selectedVal]) // //**************************************************************************// function changeSelect(fieldObj, valuesAry, optTextAry, selectedValue) { //Clear the select list fieldObj.options.length = 0; //Set the option text to the values if not passed optTextAry = (optTextAry)?optTextAry:valuesAry; //Itterate through the list and create the options for (i in valuesAry) { selectFlag = (selectedValue && selectedValue==valuesAry[i])?true:false; fieldObj.options[fieldObj.length] = new Option(optTextAry[i], valuesAry[i], false, selectFlag); } } </script> </head> <body onload="setRegions();"> <div id="wrapper"> <div id="branding"> <img border="0" src="images/banner.gif" width="800" height="120" alt="Holiday Owners Direct"/> </div><!--End Branding--> <div id="content"> <div id="logo"> <h1 id="title">Home Owners Direct</h1> <div id="search"> <?php if (isset($_SESSION['user_id']) AND (substr($_SERVER['PHP_SELF'], -10) != 'logout.php')) { $name=$_SESSION['first_name']; echo "$name you are logged in"; }else{ echo "You have not logged in"; } ?> </div> <div class="float-divider"></div> </div> <div id="postheader"> <?php $currentPage = basename($_SERVER['SCRIPT_NAME']);?> <p class="breadcrumbs"><a href="index.php">Home</a> >> <?php echo"$currentPage";?></p> <p class="post-msg"><a href="view_browse_list.php">view browse list</a></p> <div class="float-divider"></div> </div> <p> <span class="hr border"></span> The first part of the form <h1>Register Your Timeshare</h1> <form action="js.php" method="post"> <fieldset> <legend>RCI Reference Detail</legend> <p> <label for="rci_ref">RCI Reference:<em class="required">(required - numeric)</em></label> <input type="text" name="rci_ref" size="10" maxlength="10" value="<?php if (isset($_POST['rci_ref'])) echo $_POST['rci_ref']; ?>" /></p> <p> <label for="resort_name">Resort Name:</label> <input type="text" name="resort_name" size="35" maxlength="30" value="<?php if (isset($_POST['resort_name'])) echo $_POST['resort_name']; ?>" /></p> <p>Need to select country and Region from drop down list</p> <p> <label for="country">Country:</label> <select name="country" id="country" onchange="setRegions();"> <option value="Spain"<?php if ($_POST['country']=='Spain') echo ' selected'; ?>>Spain</option> <option value="France"<?php if ($_POST['country']=='France') echo ' selected'; ?>>France</option> <option value="United States"<?php if ($_POST['country']=='United States') echo ' selected'; ?>>United States</option> </select> <p> <label for="region">Region of Country:</label> <select name="region" id="region"></select> </fieldset> The first part of the validation [code] // Handle the form. if (isset($_POST['submitted'])) { require_once ('./mysql_connect2.php'); // Connect to the database. //check for rci reference if(isset($_POST['rci_ref']) && is_numeric($_POST['rci_ref'])) { $rc= escape_data($_POST['rci_ref']); } else{ $rc = FALSE; echo '<p><font color="red" size="+1">Please enter rci reference. Must be Numeric!</font></p>'; } //check for resort name if (eregi ('^[[:alpha:]\.\' \-]{2,15}$', stripslashes(trim($_POST['resort_name'])))) { $rn = escape_data($_POST['resort_name']); } else { $rn = FALSE; echo '<p><font color="red" size="+1">Please enter resort name!</font></p>'; } //check for Country if (eregi ('^[[:alpha:]\.\' \-]{2,15}$', stripslashes(trim($_POST['country'])))) { $ct = escape_data($_POST['country']); } else { $ct = FALSE; echo '<p><font color="red" size="+1">Please enter Country!</font></p>'; } //check for Region if (eregi ('^[[:alpha:]\.\' \-]{2,15}$', stripslashes(trim($_POST['region'])))) { $rg = escape_data($_POST['region']); } else { $rg = FALSE; echo '<p><font color="red" size="+1">Please enter region of the country!</font></p>'; } [/code] Thanks for your interest. Quote Link to comment https://forums.phpfreaks.com/topic/66366-how-do-i-populate-a-drop-down-list-in-a-form-on-the-basis-of-a-first-selection/#findComment-333193 Share on other sites More sharing options...
Lassie Posted August 24, 2007 Author Share Posted August 24, 2007 Hi mjdamato I forgot the html output. The erros in the script is Line 27 Char 1 Error: Object required Code 0 Url:.....js.php This also causes the query on the db to fail with Column Count doesnt match count at row 1. Which i guess means we dont have avalue for country. Quote Link to comment https://forums.phpfreaks.com/topic/66366-how-do-i-populate-a-drop-down-list-in-a-form-on-the-basis-of-a-first-selection/#findComment-333201 Share on other sites More sharing options...
Psycho Posted August 24, 2007 Share Posted August 24, 2007 Well, I'm not seeing the problem. Can you attach the entire php code? Quote Link to comment https://forums.phpfreaks.com/topic/66366-how-do-i-populate-a-drop-down-list-in-a-form-on-the-basis-of-a-first-selection/#findComment-333208 Share on other sites More sharing options...
Lassie Posted August 24, 2007 Author Share Posted August 24, 2007 This is the whole page. <?php #register property session_start(); // Include the configuration file for error management and such. require_once ('./includes/config.inc.php'); // Set the page title and include the HTML header. $page_title = 'Register a Property'; include ('./includes/header_js.htm'); $u= $_SESSION['user_id']; // Handle the form. if (isset($_POST['submitted'])) { require_once ('./mysql_connect2.php'); // Connect to the database. //check for rci reference if(isset($_POST['rci_ref']) && is_numeric($_POST['rci_ref'])) { $rc= escape_data($_POST['rci_ref']); } else{ $rc = FALSE; echo '<p><font color="red" size="+1">Please enter rci reference. Must be Numeric!</font></p>'; } //check for resort name if (eregi ('^[[:alpha:]\.\' \-]{2,15}$', stripslashes(trim($_POST['resort_name'])))) { $rn = escape_data($_POST['resort_name']); } else { $rn = FALSE; echo '<p><font color="red" size="+1">Please enter resort name!</font></p>'; } //check for Country if (eregi ('^[[:alpha:]\.\' \-]{2,15}$', stripslashes(trim($_POST['country'])))) { $ct = escape_data($_POST['country']); } else { $ct = FALSE; echo '<p><font color="red" size="+1">Please enter Country!</font></p>'; } //check for Region if (eregi ('^[[:alpha:]\.\' \-]{2,15}$', stripslashes(trim($_POST['region'])))) { $rg = escape_data($_POST['region']); } else { $rg = FALSE; echo '<p><font color="red" size="+1">Please enter region of the country!</font></p>'; } //Check type of accommodation. if($_POST['type']) { $tp= escape_data($_POST['type']); } else{ $tp = FALSE; echo '<p><font color="red" size="+1">Please select your unit type!</font></p>'; } //Check for unit number. if($_POST['unit_num']) { $un= escape_data($_POST['unit_num']); } else{ $un = FALSE; echo '<p><font color="red" size="+1">Please enter your unit number!</font></p>'; } //Check floor type. if($_POST['floor_type']) { $ft= escape_data($_POST['floor_type']); } else{ $ft= FALSE; echo '<p><font color="red" size="+1">Please select your floor type!</font></p>'; } //Check type of ownership. if($_POST['ownership']) { $ow= escape_data($_POST['ownership']); } else{ $ow = FALSE; echo '<p><font color="red" size="+1">Please select your ownership type!</font></p>'; } //Check type of period eg red, blue, etc. if($_POST['color']) { $cl= escape_data($_POST['color']); } else{ $cl = FALSE; echo '<p><font color="red" size="+1">Please indicate your period color!</font></p>'; } //Check for occupation week. if($_POST['occ_wk']) { $oc= escape_data($_POST['occ_wk']); } else{ $oc = FALSE; echo '<p><font color="red" size="+1">Please select your unit type!</font></p>'; } //Check type of booked weeks. if($_POST['booked']) { $bk= escape_data($_POST['booked']); } else{ $bk = FALSE; echo '<p><font color="red" size="+1">Please confirm if week booked or not!</font></p>'; } //Check availability for sale. if($_POST['month']) { $m= escape_data($_POST['month']); } else{ $m = FALSE; echo '<p><font color="red" size="+1">Please enter month!</font></p>'; } //Check availability for sale. if($_POST['day']) { $dy= escape_data($_POST['day']); } else{ $dy = FALSE; echo '<p><font color="red" size="+1">Please enter day of month!</font></p>'; } //Check availability for sale. if($_POST['year']) { $y= escape_data($_POST['year']); } else{ $y = FALSE; echo '<p><font color="red" size="+1">Please enter year!</font></p>'; } if (!checkdate($m,$dy,$y)) { $error = 'You have used an invalid date'; } else { $dy = $dy < 10 ? '0'.$dy : $dy; $mysqlFormat = "$y-$m-$dy"; $av=$mysqlFormat; } //Check for price. if($_POST['price']) { $p= escape_data($_POST['price']); } else{ $p = FALSE; echo '<p><font color="red" size="+1">Please enter Sale Price!</font></p>'; } //Check for offers. if($_POST['offers']) { $o= escape_data($_POST['offers']); } else{ $o = FALSE; echo '<p><font color="red" size="+1">Please indicate whether you will take offers!</font></p>'; } //Check for trustees. if($_POST['trustees']) { $t= escape_data($_POST['trustees']); } else{ $t = FALSE; echo '<p><font color="red" size="+1">Please enter your trustees name!</font></p>'; } //Check for property description. if($_POST['description']) { $d= escape_data($_POST['description']); } else{ $d = FALSE; echo '<p><font color="red" size="+1">Please describe your property!</font></p>'; } if ($rc && $rn && $ct && $rg && $tp && $un && $ft && $ow && $cl && $oc && $bk && $av && $p && $o && $t && $d) { //If everything OK $v=$_SESSION['user_id']; //add the property $query = "INSERT INTO property (v_id,rci_ref,country,region,resort_name,unit_desc,unit_num,floor_type,ownership,floating, occ_wk,booked,available,price,offers,trustees,description) VALUES ($v,$rc,'$ct','$rg','$rn','$tp','$un','$ft','$ow','$cl','$oc','$bk','$av','$p','$o','$t','$d')"; $result = mysql_query ($query) or trigger_error("Query: $query\n<br />MySQL Error: " . mysql_error()); if (mysql_affected_rows() == 1) { // If it ran OK. //log the advertisement //get last property_id $property_id = mysql_insert_id(); $query = "INSERT INTO ads VALUES ('','$u',NOW(),'','','$property_id')"; $result = mysql_query ($query) or die(mysql_error()); // $result = mysql_query($query); if (!mysql_affected_rows() == 1) { echo "Your Property could not be registered due to a system error.Please contact admin@homeownersdirect"; exit(); } //if it ran ok //update property record with ad ref $ad_ref = mysql_insert_id(); $query = "UPDATE property SET ad_ref ='$ad_ref' WHERE property_id = '$property_id'"; $result = mysql_query ($query) or trigger_error("Query: $query\n<br />MySQL Error: " . mysql_error()); $result = mysql_query($query); if (!$result) { echo "Your Property could not be registered due to a system error.Please contact admin@homeownersdirect"; exit(); } // Start defining the URL. $url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']); // Check for a trailing slash. if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) { $url = substr ($url, 0, -1); // Chop off the slash. } // Add the page. $url .= '/Prop_payment.php'; ob_end_clean(); // Delete the buffer. header("Location: $url"); exit(); }else{ echo "Your Property could not be registered due to a system error.Please contact admin@homeownersdirect"; exit(); } } else { // If one of the data tests failed. echo '<p><font color="red" size="+1">Please try again.</font></p>'; } mysql_close(); // Close the database connection. } // End of the main Submit conditional. ?> <h1>Register Your Timeshare</h1> <form action="js.php" method="post"> <fieldset> <legend>RCI Reference Detail</legend> <p> <label for="rci_ref">RCI Reference:<em class="required">(required - numeric)</em></label> <input type="text" name="rci_ref" size="10" maxlength="10" value="<?php if (isset($_POST['rci_ref'])) echo $_POST['rci_ref']; ?>" /></p> <p> <label for="resort_name">Resort Name:</label> <input type="text" name="resort_name" size="35" maxlength="30" value="<?php if (isset($_POST['resort_name'])) echo $_POST['resort_name']; ?>" /></p> <p>Need to select country and Region from drop down list</p> <p> <label for="country">Country:</label> <select name="country" id="country" onchange="setRegions();"> <option value="Spain"<?php if ($_POST['country']=='Spain') echo ' selected'; ?>>Spain</option> <option value="France"<?php if ($_POST['country']=='France') echo ' selected'; ?>>France</option> <option value="United States"<?php if ($_POST['country']=='United States') echo ' selected'; ?>>United States</option> </select> <p> <label for="region">Region of Country:</label> <select name="region" id="region"></select> </fieldset> <fieldset> <legend>Unit Details</legend> <p> <label for="select">Please select your unit type</label> <select name="type"> <option value="No selection" <?php if(!$_POST || $_POST['type']== 'No selection') { ?>selected="selected" <?php }?> >Select one</option> <option value="T0">Studio</option> <option value="T1">1 Bed</option> <option value="T2">2 Bed</option> <option value="T3">Other</option> </select> </p> <p> <label for="unit_num">Unit Number:</label> <input type="text" name="unit_num" size="10" maxlength="6" value="<?php if (isset($_POST['unit_num'])) echo $_POST['unit_num']; ?>" /></p> <p> <label for="select">Please select your unit type</label> <select name="floor_type"> <option value="No selection" <?php if(!$_POST || $_POST['type']== 'No selection') { ?>selected="selected" <?php }?> >Select one</option> <option value="ground">Ground</option> <option value="first">First</option> <option value="second">Second</option> <option value="third">Third</option> </select> </p> <p> <label for="ownership">Please select your ownership type</label> <select name="ownership"> <option value="No selection" <?php if(!$_POST || $_POST['ownership']== 'No selection') { ?>selected="selected" <?php }?> >Select one</option> <option value="floating">Floating</option> <option value="fixed">Fixed</option> </select> </p> <p> <label for="color">If Floating ownership indicate period</label> <select name="color"> <option value="No selection" <?php if(!$_POST || $_POST['color']== 'No selection') { ?>selected="selected" <?php }?> >Select one</option> <option value="red">RED</option> <option value="blue">Blue</option> <option value="white">White</option> <option value="other">Other</option> </select> </p> <p> <label for="occ_wk">If Fixed please enter week:</label> <input type="text" name="occ_wk" size="10" maxlength="6" value="<?php if (isset($_POST['occ_wk'])) echo $_POST['occ_wk']; ?>" /></p> <p> <label for="select">Please indicate whether week is booked.</label> <select name="booked"> <option value="No selection" <?php if(!$_POST || $_POST['booked']== 'No selection') { ?>selected="selected" <?php }?> >Select one</option> <option value="yes">Yes</option> <option value="no">No</option> </select> </p> <p> <b>When will it be available for Sale?</b><em class="required">(MM/DD/YYYY)</em> </p> <p> <?php // This script makes three pull-down menus for an HTML form: months, days, years. // Make the months array. $month = array (1 => 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'); // Make the months pull-down menu. echo '<select name="month">'; foreach ($month as $key => $value) { echo "<option value=\"$key\">$value</option>\n"; } echo '</select>'; // Make the days pull-down menu. echo '<select name="day">'; for ($day = 1; $day <= 31; $day++) { echo "<option value=\"$day\">$day</option>\n"; } echo '</select>'; // Make the years pull-down menu. echo '<select name="year">'; $year = 2007; while ($year <= 2015) { echo "<option value=\"$year\">$year</option>\n"; $year++; } echo '</select>'; ?> </fieldset> <fieldset> <legend>Commercial Details</legend> <p> <label for="price">What is your asking price?</label> <input type="text" name="price" size="10" maxlength="6" value="<?php if (isset($_POST['price'])) echo $_POST['price']; ?>" /></p> <p> <label for="offers">Please indicate whether you will consider offers.</label> <select name="offers"> <option value="No selection" <?php if(!$_POST || $_POST['offers']== 'No selection') { ?>selected="selected" <?php }?> >Select one</option> <option value="yes">Yes</option> <option value="no">No</option> </select> </p> <p> <label for="trustees">Who are your Trustees?</label> <input type="text" name="trustees" size="35" maxlength="30" value="<?php if (isset($_POST['trustees'])) echo $_POST['trustees']; ?>" /></p> <p> <label for="description">Description:</label> <textarea name="description" id="description" cols="50" rows="10"> </textarea> </p> <div align="center"><input type="submit" name="submit" value="submit" /></div> <input type="hidden" name="submitted" value="TRUE" /> </fieldset> </form> <?php // Include the HTML footer. include ('./includes/footer.html'); ?> Quote Link to comment https://forums.phpfreaks.com/topic/66366-how-do-i-populate-a-drop-down-list-in-a-form-on-the-basis-of-a-first-selection/#findComment-333212 Share on other sites More sharing options...
Psycho Posted August 24, 2007 Share Posted August 24, 2007 Ok, I've gone through this and I think the PHP error was due the POST variables not being set on the first load of the page and the code I used to auto-select the previous value was not handling that properly. I'm not 100% sure about the javascript error, but I think it was due to the PHP error mucking up the value that the javascript was using. Now, because you need the previously selected values auto-populated in case there is a validation error thre needs to be logic both within the javascript and the PHP that can handle the dynamic region list. To make things easier I have modified the code so that you only need to specify the country/region associattions once and all the other code (PHP & Javascript) will react accordingly. In the main PHP page I have added this at the top of the page where you will modify the regionList array //********************************************************** //*** Modify regionlist to change the country/region options //********************************************************** $regionList['Spain'] = array('Almeria', 'Costa del Sol'); $regionList['France'] = array('Midi-Pyrenees', 'Languedoc-Roussillon','Aquitane'); $regionList['United States'] = array('Arizona','Florida'); //********************************************************** Then immediately following that I used this code to set the selected values and the region list based upon whether it is a first load or ther are posted values (in case of validation errors) $countries = array_keys($regions); $countrySel = (isset($_POST['country']) && in_array($_POST['country'],$countries))?$_POST['country']:$countries[0]; $regions = $regionList[$countrySel]; $regionSel = (isset($_POST['region']) && in_array($_POST['region'],$regions))?$_POST['region']:$regions[0]; Then in the form I used the values from above to create the select list options and select the appropriate value <p>Need to select country and Region from drop down list</p> <p> <label for="country">Country:</label> <select name="country" id="country" onchange="setRegions();"> <?php //Create the country select list foreach ($countries as $country) { echo "<option value=\"$country\"".(($country==$countrySel)?' selected':'').">$country</option>"; } ?> </select> <p> <label for="region">Region of Country:</label> <select name="region" id="region"> <?php //Create the region select list foreach ($regions as $region) { echo "<option value=\"$region\"".(($region==$regionSel)?' selected':'').">$region</option>"; } ?> </select> Lastly, I did not see the javascript in the page above, so I am assuming it is in the include file. You will want to have the javascript created in the PHP code so that you can dynamically create the javascript arrays from the PHP array. So replace this <script type="text/javascript"> // Region lists var regions = new Array(); regions['Spain'] = new Array('Almeria', 'Costa del Sol'); regions['France'] = new Array('Midi-Pyrenees', 'Languedoc-Roussillon','Aquitane'); regions['United States'] = new Array('Arizona','Florida'); function setRegions(){ With this <script type="text/javascript"> // Region lists var regions = new Array(); <?php foreach ($regionList as $country => $regions) { echo "regions['$country'] = new Array ('" . implode("', '", $regions) . ",);\n"; } ?> function setRegions(){ EDIT: I have attached the main php page in its entirety. [attachment deleted by admin] Quote Link to comment https://forums.phpfreaks.com/topic/66366-how-do-i-populate-a-drop-down-list-in-a-form-on-the-basis-of-a-first-selection/#findComment-333288 Share on other sites More sharing options...
Lassie Posted August 25, 2007 Author Share Posted August 25, 2007 Many thanks Mjdamato. I will try this and let you know the outcome. I see the logic of what you say. Thanks again and yes the js was in the include file. Quote Link to comment https://forums.phpfreaks.com/topic/66366-how-do-i-populate-a-drop-down-list-in-a-form-on-the-basis-of-a-first-selection/#findComment-333785 Share on other sites More sharing options...
Lassie Posted August 25, 2007 Author Share Posted August 25, 2007 Hi Mjadamato Many thanks for you interest. I have tried the new version and get 2 script errors which i assume is js as follows Line 17 Untermninated string constant and Line 57 Object expected. I post both the page and the header with the js below. Can you suggest how I fix this please. php page <?php #register property // Include the configuration file for error management and such. require_once ('./includes/config.inc.php'); // Set the page title and include the HTML header. $page_title = 'Register a Property'; session_start(); //********************************************************** //*** Modify regionlist to change the country/region options //********************************************************** $regionList['Spain'] = array('Almeria', 'Costa del Sol'); $regionList['France'] = array('Midi-Pyrenees', 'Languedoc-Roussillon','Aquitane'); $regionList['United States'] = array('Arizona','Florida'); //********************************************************** $countries = array_keys($regions); $countrySel = (isset($_POST['country']) && in_array($_POST['country'],$countries))?$_POST['country']:$countries[0]; $regions = $regionList[$countrySel]; $regionSel = (isset($_POST['region']) && in_array($_POST['region'],$regions))?$_POST['region']:$regions[0]; include ('./includes/header_js.htm'); $u= $_SESSION['user_id']; // Handle the form. if (isset($_POST['submitted'])) { require_once ('./mysql_connect2.php'); // Connect to the database. //check for rci reference if(isset($_POST['rci_ref']) && is_numeric($_POST['rci_ref'])) { $rc= escape_data($_POST['rci_ref']); } else{ $rc = FALSE; echo '<p><font color="red" size="+1">Please enter rci reference. Must be Numeric!</font></p>'; } //check for resort name if (eregi ('^[[:alpha:]\.\' \-]{2,15}$', stripslashes(trim($_POST['resort_name'])))) { $rn = escape_data($_POST['resort_name']); } else { $rn = FALSE; echo '<p><font color="red" size="+1">Please enter resort name!</font></p>'; } //check for Country if (eregi ('^[[:alpha:]\.\' \-]{2,15}$', stripslashes(trim($_POST['country'])))) { $ct = escape_data($_POST['country']); } else { $ct = FALSE; echo '<p><font color="red" size="+1">Please enter Country!</font></p>'; } //check for Region if (eregi ('^[[:alpha:]\.\' \-]{2,15}$', stripslashes(trim($_POST['region'])))) { $rg = escape_data($_POST['region']); } else { $rg = FALSE; echo '<p><font color="red" size="+1">Please enter region of the country!</font></p>'; } //Check type of accommodation. if($_POST['type']) { $tp= escape_data($_POST['type']); } else{ $tp = FALSE; echo '<p><font color="red" size="+1">Please select your unit type!</font></p>'; } //Check for unit number. if($_POST['unit_num']) { $un= escape_data($_POST['unit_num']); } else{ $un = FALSE; echo '<p><font color="red" size="+1">Please enter your unit number!</font></p>'; } //Check floor type. if($_POST['floor_type']) { $ft= escape_data($_POST['floor_type']); } else{ $ft= FALSE; echo '<p><font color="red" size="+1">Please select your floor type!</font></p>'; } //Check type of ownership. if($_POST['ownership']) { $ow= escape_data($_POST['ownership']); } else{ $ow = FALSE; echo '<p><font color="red" size="+1">Please select your ownership type!</font></p>'; } //Check type of period eg red, blue, etc. if($_POST['color']) { $cl= escape_data($_POST['color']); } else{ $cl = FALSE; echo '<p><font color="red" size="+1">Please indicate your period color!</font></p>'; } //Check for occupation week. if($_POST['occ_wk']) { $oc= escape_data($_POST['occ_wk']); } else{ $oc = FALSE; echo '<p><font color="red" size="+1">Please select your unit type!</font></p>'; } //Check type of booked weeks. if($_POST['booked']) { $bk= escape_data($_POST['booked']); } else{ $bk = FALSE; echo '<p><font color="red" size="+1">Please confirm if week booked or not!</font></p>'; } //Check availability for sale. if($_POST['month']) { $m= escape_data($_POST['month']); } else{ $m = FALSE; echo '<p><font color="red" size="+1">Please enter month!</font></p>'; } //Check availability for sale. if($_POST['day']) { $dy= escape_data($_POST['day']); } else{ $dy = FALSE; echo '<p><font color="red" size="+1">Please enter day of month!</font></p>'; } //Check availability for sale. if($_POST['year']) { $y= escape_data($_POST['year']); } else{ $y = FALSE; echo '<p><font color="red" size="+1">Please enter year!</font></p>'; } if (!checkdate($m,$dy,$y)) { $error = 'You have used an invalid date'; } else { $dy = $dy < 10 ? '0'.$dy : $dy; $mysqlFormat = "$y-$m-$dy"; $av=$mysqlFormat; } //Check for price. if($_POST['price']) { $p= escape_data($_POST['price']); } else{ $p = FALSE; echo '<p><font color="red" size="+1">Please enter Sale Price!</font></p>'; } //Check for offers. if($_POST['offers']) { $o= escape_data($_POST['offers']); } else{ $o = FALSE; echo '<p><font color="red" size="+1">Please indicate whether you will take offers!</font></p>'; } //Check for trustees. if($_POST['trustees']) { $t= escape_data($_POST['trustees']); } else{ $t = FALSE; echo '<p><font color="red" size="+1">Please enter your trustees name!</font></p>'; } //Check for property description. if($_POST['description']) { $d= escape_data($_POST['description']); } else{ $d = FALSE; echo '<p><font color="red" size="+1">Please describe your property!</font></p>'; } if ($rc && $rn && $ct && $rg && $tp && $un && $ft && $ow && $cl && $oc && $bk && $av && $p && $o && $t && $d) { //If everything OK $v=$_SESSION['user_id']; //add the property $query = "INSERT INTO property (v_id,rci_ref,country,region,resort_name,unit_desc,unit_num,floor_type,ownership,floating, occ_wk,booked,available,price,offers,trustees,description) VALUES ($v,$rc,'$ct','$rg','$rn','$tp','$un','$ft','$ow','$cl','$oc','$bk','$av','$p','$o','$t','$d')"; $result = mysql_query ($query) or trigger_error("Query: $query\n<br />MySQL Error: " . mysql_error()); if (mysql_affected_rows() == 1) { // If it ran OK. //log the advertisement //get last property_id $property_id = mysql_insert_id(); $query = "INSERT INTO ads VALUES ('','$u',NOW(),'','','$property_id')"; $result = mysql_query ($query) or die(mysql_error()); // $result = mysql_query($query); if (!mysql_affected_rows() == 1) { echo "Your Property could not be registered due to a system error.Please contact admin@homeownersdirect"; exit(); } //if it ran ok //update property record with ad ref $ad_ref = mysql_insert_id(); $query = "UPDATE property SET ad_ref ='$ad_ref' WHERE property_id = '$property_id'"; $result = mysql_query ($query) or trigger_error("Query: $query\n<br />MySQL Error: " . mysql_error()); $result = mysql_query($query); if (!$result) { echo "Your Property could not be registered due to a system error.Please contact admin@homeownersdirect"; exit(); } // Start defining the URL. $url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']); // Check for a trailing slash. if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) { $url = substr ($url, 0, -1); // Chop off the slash. } // Add the page. $url .= '/Prop_payment.php'; ob_end_clean(); // Delete the buffer. header("Location: $url"); exit(); }else{ echo "Your Property could not be registered due to a system error.Please contact admin@homeownersdirect"; exit(); } } else { // If one of the data tests failed. echo '<p><font color="red" size="+1">Please try again.</font></p>'; } mysql_close(); // Close the database connection. } // End of the main Submit conditional. ?> <h1>Register Your Timeshare</h1> <form action="js.php" method="post"> <fieldset> <legend>RCI Reference Detail</legend> <p> <label for="rci_ref">RCI Reference:<em class="required">(required - numeric)</em></label> <input type="text" name="rci_ref" size="10" maxlength="10" value="<?php if (isset($_POST['rci_ref'])) echo $_POST['rci_ref']; ?>" /></p> <p> <label for="resort_name">Resort Name:</label> <input type="text" name="resort_name" size="35" maxlength="30" value="<?php if (isset($_POST['resort_name'])) echo $_POST['resort_name']; ?>" /></p> <p>Need to select country and Region from drop down list</p> <p> <label for="country">Country:</label> <select name="country" id="country" onchange="setRegions();"> <?php //Create the country select list foreach ($countries as $country) { echo "<option value=\"$country\"".(($country==$countrySel)?' selected':'').">$country</option>"; } ?> </select> <p> <label for="region">Region of Country:</label> <select name="region" id="region"> <?php //Create the region select list foreach ($regions as $region) { echo "<option value=\"$region\"".(($region==$regionSel)?' selected':'').">$region</option>"; } ?> </select> </fieldset> <fieldset> <legend>Unit Details</legend> <p> <label for="select">Please select your unit type</label> <select name="type"> <option value="No selection" <?php if(!$_POST || $_POST['type']== 'No selection') { ?>selected="selected" <?php }?> >Select one</option> <option value="T0">Studio</option> <option value="T1">1 Bed</option> <option value="T2">2 Bed</option> <option value="T3">Other</option> </select> </p> <p> <label for="unit_num">Unit Number:</label> <input type="text" name="unit_num" size="10" maxlength="6" value="<?php if (isset($_POST['unit_num'])) echo $_POST['unit_num']; ?>" /></p> <p> <label for="select">Please select your unit type</label> <select name="floor_type"> <option value="No selection" <?php if(!$_POST || $_POST['type']== 'No selection') { ?>selected="selected" <?php }?> >Select one</option> <option value="ground">Ground</option> <option value="first">First</option> <option value="second">Second</option> <option value="third">Third</option> </select> </p> <p> <label for="ownership">Please select your ownership type</label> <select name="ownership"> <option value="No selection" <?php if(!$_POST || $_POST['ownership']== 'No selection') { ?>selected="selected" <?php }?> >Select one</option> <option value="floating">Floating</option> <option value="fixed">Fixed</option> </select> </p> <p> <label for="color">If Floating ownership indicate period</label> <select name="color"> <option value="No selection" <?php if(!$_POST || $_POST['color']== 'No selection') { ?>selected="selected" <?php }?> >Select one</option> <option value="red">RED</option> <option value="blue">Blue</option> <option value="white">White</option> <option value="other">Other</option> </select> </p> <p> <label for="occ_wk">If Fixed please enter week:</label> <input type="text" name="occ_wk" size="10" maxlength="6" value="<?php if (isset($_POST['occ_wk'])) echo $_POST['occ_wk']; ?>" /></p> <p> <label for="select">Please indicate whether week is booked.</label> <select name="booked"> <option value="No selection" <?php if(!$_POST || $_POST['booked']== 'No selection') { ?>selected="selected" <?php }?> >Select one</option> <option value="yes">Yes</option> <option value="no">No</option> </select> </p> <p> <b>When will it be available for Sale?</b><em class="required">(MM/DD/YYYY)</em> </p> <p> <?php // This script makes three pull-down menus for an HTML form: months, days, years. // Make the months array. $month = array (1 => 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'); // Make the months pull-down menu. echo '<select name="month">'; foreach ($month as $key => $value) { echo "<option value=\"$key\">$value</option>\n"; } echo '</select>'; // Make the days pull-down menu. echo '<select name="day">'; for ($day = 1; $day <= 31; $day++) { echo "<option value=\"$day\">$day</option>\n"; } echo '</select>'; // Make the years pull-down menu. echo '<select name="year">'; $year = 2007; while ($year <= 2015) { echo "<option value=\"$year\">$year</option>\n"; $year++; } echo '</select>'; ?> </fieldset> <fieldset> <legend>Commercial Details</legend> <p> <label for="price">What is your asking price?</label> <input type="text" name="price" size="10" maxlength="6" value="<?php if (isset($_POST['price'])) echo $_POST['price']; ?>" /></p> <p> <label for="offers">Please indicate whether you will consider offers.</label> <select name="offers"> <option value="No selection" <?php if(!$_POST || $_POST['offers']== 'No selection') { ?>selected="selected" <?php }?> >Select one</option> <option value="yes">Yes</option> <option value="no">No</option> </select> </p> <p> <label for="trustees">Who are your Trustees?</label> <input type="text" name="trustees" size="35" maxlength="30" value="<?php if (isset($_POST['trustees'])) echo $_POST['trustees']; ?>" /></p> <p> <label for="description">Description:</label> <textarea name="description" id="description" cols="50" rows="10"> </textarea> </p> <div align="center"><input type="submit" name="submit" value="submit" /></div> <input type="hidden" name="submitted" value="TRUE" /> </fieldset> </form> <?php // Include the HTML footer. include ('./includes/footer.html'); ?> header with js [code] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml2/DTD/xhtml1-strict. dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Timeshare1</title> <style type="text/css" media="screen">@import "./includes/layout.css";</style> <style type="text/css" media="screen">@import "./includes/full.css";</style> <!--[if lte IE 6] <style type="text/css" media="screen">@import "./includes/flyout_ie.css";</style> <![endif]--> </head> <script type="text/javascript"> // Region lists var regions = new Array(); <?php foreach ($regionList as $country => $regions) { echo "regions['$country'] = new Array ('" . implode("', '", $regions) . ",);\n"; } ?> function setRegions(){ cntrySel = document.getElementById('country'); regionSel = document.getElementById('region'); regionList = regions[cntrySel.value]; changeSelect(regionSel, regionList); } //**************************************************************************// // FUNCTION changeSelect(fieldObj, valuesAry, [optTextAry], [selectedVal]) // //**************************************************************************// function changeSelect(fieldObj, valuesAry, optTextAry, selectedValue) { //Clear the select list fieldObj.options.length = 0; //Set the option text to the values if not passed optTextAry = (optTextAry)?optTextAry:valuesAry; //Itterate through the list and create the options for (i in valuesAry) { selectFlag = (selectedValue && selectedValue==valuesAry[i])?true:false; fieldObj.options[fieldObj.length] = new Option(optTextAry[i], valuesAry[i], false, selectFlag); } } </script> </head> <body onload="setRegions();"> <div id="wrapper"> <div id="branding"> <img border="0" src="images/banner.gif" width="800" height="120" alt="Holiday Owners Direct"/> </div><!--End Branding--> <div id="content"> <div id="logo"> <h1 id="title">Home Owners Direct</h1> <div id="search"> <?php if (isset($_SESSION['user_id']) AND (substr($_SERVER['PHP_SELF'], -10) != 'logout.php')) { $name=$_SESSION['first_name']; echo "$name you are logged in"; }else{ echo "You have not logged in"; } ?> </div> <div class="float-divider"></div> </div> <div id="postheader"> <?php $currentPage = basename($_SERVER['SCRIPT_NAME']);?> <p class="breadcrumbs"><a href="index.php">Home</a> >> <?php echo"$currentPage";?></p> <p class="post-msg"><a href="view_browse_list.php">view browse list</a></p> <div class="float-divider"></div> </div> <p> <span class="hr border"></span> [/code] Quote Link to comment https://forums.phpfreaks.com/topic/66366-how-do-i-populate-a-drop-down-list-in-a-form-on-the-basis-of-a-first-selection/#findComment-333802 Share on other sites More sharing options...
Psycho Posted August 25, 2007 Share Posted August 25, 2007 Do you have a link where I can see the page as it is produced? It would be much easier to find the problem that way. Also, if your verification code, I think you could make it more efficient by doing someting such as this: Change this <?php //Check for offers. if($_POST['offers']) { $o= escape_data($_POST['offers']); } else{ $o = FALSE; echo '<p><font color="red" size="+1">Please indicate whether you will take offers!</font></p>'; } ?> To this: <?php //Check for offers. $o = ($_POST['offers']) ? escape_data($_POST['offers']) : false; if (!$o) { echo '<p><font color="red" size="+1">Please indicate whether you will take offers!</font></p>'; } ?> Quote Link to comment https://forums.phpfreaks.com/topic/66366-how-do-i-populate-a-drop-down-list-in-a-form-on-the-basis-of-a-first-selection/#findComment-334024 Share on other sites More sharing options...
Lassie Posted August 27, 2007 Author Share Posted August 27, 2007 Hi Mjdamato, Sorry to be slow coming back - holiday commitments You can find the page on this link http://217.46.159.226/timeshare5/js2.php The country drop down is not populating I forgot to mention. Thanks for the validation suggestion. I will look at that. Quote Link to comment https://forums.phpfreaks.com/topic/66366-how-do-i-populate-a-drop-down-list-in-a-form-on-the-basis-of-a-first-selection/#findComment-335082 Share on other sites More sharing options...
Lassie Posted August 27, 2007 Author Share Posted August 27, 2007 Hi Mjadamato, I checked the errors log and there is the following line 18 First argument to array_keys() should be an array. Could you just reiterate the order in which this code needs to fit together. At present ihave the following the js header with the php code to go through the region array etc the php code at the top of the page to modify the region list and the select code in the form. Any help you can give is most appreciated. Quote Link to comment https://forums.phpfreaks.com/topic/66366-how-do-i-populate-a-drop-down-list-in-a-form-on-the-basis-of-a-first-selection/#findComment-335248 Share on other sites More sharing options...
Psycho Posted August 27, 2007 Share Posted August 27, 2007 The PHP code with the region list needs to come before the js code because the js code uses the PHP region list array to create the region list array in the js code. Quote Link to comment https://forums.phpfreaks.com/topic/66366-how-do-i-populate-a-drop-down-list-in-a-form-on-the-basis-of-a-first-selection/#findComment-335339 Share on other sites More sharing options...
Psycho Posted August 27, 2007 Share Posted August 27, 2007 OK, I looked at your page as well as the code provided and found some other problems. Typos as well as me resuing a variable I shouldn't have. Anyway, I have created a test page to make sure everything is working correctly. You should be able to copy out the code to the appropriate places. Here is the test page <?php //********************************************************** //*** Modify regionlist to change the country/region options //********************************************************** $regionList['Spain'] = array('Almeria', 'Costa del Sol'); $regionList['France'] = array('Midi-Pyrenees', 'Languedoc-Roussillon','Aquitane'); $regionList['United States'] = array('Arizona','Florida'); //********************************************************** $countries = array_keys($regionList); $countrySel = (isset($_POST['country']) && in_array($_POST['country'],$countries))?$_POST['country']:$countries[0]; $regions = $regionList[$countrySel]; $regionSel = (isset($_POST['region']) && in_array($_POST['region'],$regions))?$_POST['region']:$regions[0]; ?> <html> <head> <script type="text/javascript"> // Region lists var regions = new Array(); <?php foreach ($regionList as $country => $region) { echo "regions['$country'] = new Array ('" . implode("', '", $region) . "');\n"; } ?> function setRegions(){ cntrySel = document.getElementById('country'); regionSel = document.getElementById('region'); regionList = regions[cntrySel.value]; changeSelect(regionSel, regionList); return; } //**************************************************************************// // FUNCTION changeSelect(fieldObj, valuesAry, [optTextAry], [selectedVal]) // //**************************************************************************// function changeSelect(fieldObj, valuesAry, optTextAry, selectedValue) { //Clear the select list fieldObj.options.length = 0; //Set the option text to the values if not passed optTextAry = (optTextAry)?optTextAry:valuesAry; //Itterate through the list and create the options for (i in valuesAry) { selectFlag = (selectedValue && selectedValue==valuesAry[i])?true:false; fieldObj.options[fieldObj.length] = new Option(optTextAry[i], valuesAry[i], false, selectFlag); } return; } </script> </head> <body> <p>Need to select country and Region from drop down list</p> <p> <label for="country">Country:</label> <select name="country" id="country" onchange="setRegions();"> <?php //Create the country select list foreach ($countries as $country) { echo "<option value=\"$country\"".(($country==$countrySel)?' selected':'').">$country</option>\n"; } ?> </select> <p> <label for="region">Region of Country:</label> <select name="region" id="region"> <?php //Create the region select list foreach ($regions as $region) { echo "<option value=\"$region\"".(($region==$regionSel)?' selected':'').">$region</option>\n"; } ?> </select> </body> </html> Quote Link to comment https://forums.phpfreaks.com/topic/66366-how-do-i-populate-a-drop-down-list-in-a-form-on-the-basis-of-a-first-selection/#findComment-335351 Share on other sites More sharing options...
Lassie Posted August 27, 2007 Author Share Posted August 27, 2007 Thanks I'll give that ago and let u know. Quote Link to comment https://forums.phpfreaks.com/topic/66366-how-do-i-populate-a-drop-down-list-in-a-form-on-the-basis-of-a-first-selection/#findComment-335486 Share on other sites More sharing options...
Lassie Posted August 27, 2007 Author Share Posted August 27, 2007 I have tried the test page.Is it intended to be stand alone as I dont get a populated drop down. I notice that the body tag in the test page does not included the prevoius code:- <body onload="setRegions();"># Is this still required? Quote Link to comment https://forums.phpfreaks.com/topic/66366-how-do-i-populate-a-drop-down-list-in-a-form-on-the-basis-of-a-first-selection/#findComment-335525 Share on other sites More sharing options...
Psycho Posted August 27, 2007 Share Posted August 27, 2007 Yes, the code I posted above is a fully functional, stand-alone page. I just copied and pasted the code above into a new php file and it works for me. Are you getting any errors? What is the URL of the page you creted from that code? The onload trigger is not needed because the PHP code at the top will determine the correct region list to display. That was there from a previous project that I took this code from. NOTE: If you have MSN, send me a PM with your ID and we can get this taken care of a lot faster. Quote Link to comment https://forums.phpfreaks.com/topic/66366-how-do-i-populate-a-drop-down-list-in-a-form-on-the-basis-of-a-first-selection/#findComment-335550 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.