Page 1 of 1

PHP & Drop Down Box

Posted: Thu Sep 08, 2005 3:06 pm
by quadoc
Ok, I've two drop down boxes. The first one is for the deparment and the second one is for the categories. What I'm trying to do is determine what the user has selected for the deparment and then populate the categories. I've tried and tried but still can't figure it out. Some how the Department keep reverts back to the first selection index. Could someone take the look at the following code and post some tips or have a better way of doing it. Thanks... :?

Code: Select all

<SCRIPT LANGUAGE=javascript>

function selDept(obj)
{
   document.getElementById("hidDept").value=obj.options[obj.options.selectedIndex].value

   if(document.getElementById("hidDept").value!=0)
   {					
      document.getElementById ("frmDept").submit()
   } 
}
</SCRIPT>

$i_hidDept = (isSet($_POST['hidDept'])) ? $_POST['hidDept'] : null;

if ($i_hidDept!="")
  {
    $tmpDept=$_POST["hidDept"];
  }
else
  {
    $tmpDept=1;
  } 

<form name="frmDept" id="frmDept" method="post" action="">
<input type="hidden" name="hidDept" id="hidDept" value="<? echo $tmpDept; ?>">
</form>

<form name="frmTicket" method="post" enctype="multipart/form-data">

   <tr align="left" valign="top"> 
      <td><br><font color="#<? echo $fontdep ?>">Department</font></td>
      <td><br>
	  <select name="department" id="department" onchange="javascript:selDept(this)">
    
 <?php

	$str =  "select * from tbl_departments ";	
	$res = mssql_query($str) or die(mssql_error());
			
?>

<?
			while($data = mssql_fetch_array($res))
			{												
						$tmp_dept = $data["department"];
			?>
					<option value = "<?=$data['id']?>"><?=$tmp_dept?>
					</option>
				<?
					}
				?>
</select></td>

    </tr>   
	<tr align="left" valign="top"> 
      <td width="130">Problem Type</td>
      <td width="600"> 
	  <?php
//    echo $tmpDept;
    if ($tmpDept <= 0) {$tmpDept = 1;}

//		$str = "select * from tbl_categories order by categories";
    $str = "select * from tbl_categories WHERE dept_id =".$tmpDept."";

    
		$res = mssql_query($str) or die(mssql_error());		
	  ?>
		<select name = "lst_categories">
		<?
			while($data = mssql_fetch_array($res))
			{
				$i_id = $data["id"];
				$s_categ = $data["categories"];
			?>
				<option value = "<?=$s_categ?>"> 
				<?=$s_categ?>
				</option>
			<?
			}
		?>
		</select>
	  </td>
    </tr>
</form>

Posted: Thu Sep 08, 2005 3:58 pm
by Burrito
you're not selecting the option that is selected prior to the post

try this:

Code: Select all

<option value = "<?=$data['id']?>" <?=(isset($_POST['department']) && $_POST['department'] == $data['id'] ? "selected=\"selected\"" : "");?>><?=$tmp_dept?>

Posted: Thu Sep 08, 2005 11:47 pm
by harrisonad
CoderGoblin answered that years ago :lol:
viewtopic.php?t=29084

Posted: Fri Sep 16, 2005 10:45 am
by quadoc
Burrito,

I still can't get it to work. Can I send you the script and have you tell me what I did wrong? :?

Posted: Fri Sep 16, 2005 11:02 am
by Burrito
just post it in here...

Posted: Fri Sep 16, 2005 11:10 am
by quadoc
ok here is the script.

Code: Select all

<?php

include "online.php";
?>
<SCRIPT LANGUAGE=javascript>

function selDept(obj)
{
   document.getElementById("hidDept").value=obj.options[obj.options.selectedIndex].value

   if(document.getElementById("hidDept").value!="")
   {					
      document.getElementById ("frmDept").submit()
   } 
}

if (!document.layers&&!document.all)
event="test"

function showtip(current,e,text)
{
  if (document.all){
  thetitle=text.split('<br>')
	
  if (thetitle.length>1){
    thetitles=''
    for (i=0;i<thetitle.length;i++)
    thetitles+=thetitle[i]
    current.title=thetitles
  }
  else
    current.title=text
  }

else if (document.layers){
	
  document.tooltip.document.write('<layer bgColor="white" style="border:1px solid black;font-size:12px;">'+text+'</layer>')
  document.tooltip.document.close()
  document.tooltip.left=e.pageX+7
  document.tooltip.top=e.pageY+7
  document.tooltip.visibility="show"
 }
}

function hidetip(){
if (document.layers)
document.tooltip.visibility="hidden"
}

function putValue()
{
  txt=document.forms[0].department.options[document.forms[0].department.selectedIndex].text
  document.forms[0].hidDept.value=txt
}

</SCRIPT>

<?php
$fontname = "000000";
$fontemail = "000000";
$fontsubject = "000000";
$fontcategories = "000000";
$fontmessage = "000000";
$fontdep = "000000";
$fontpir = "000000";

$upload_ftype = array("application/x-zip-compressed");
$upload_dir = "./Upload_Files/";

$i_hidDept = (isSet($_POST['hidDept'])) ? $_POST['hidDept'] : null;

if ($i_hidDept!="")
  {
    $tmpDept=$_POST["hidDept"];
  }
else {$tmpDept=1;}

// if ($tmpDept <> 0) {$_POST["department"] = $tmpDept;}

if (isset($_POST["department"]))

{
	$error = 0;
	$upload_flag = 0;
	$subname = $_POST["username"];
	$subemail = $_POST["email"];
	//$subsubject = $_POST["subject"];
	$subsubject = $_POST["subject"];
	$subcategories = $_POST["lst_categories"];

  
	//$submessage = htmlspecialchars($_POST["message"]);
	$submessage = $_POST["message"];
	
	/*
	$submessage = preg_replace("/\r/","",$submessage);
	$submessage = preg_replace("/\n/","",$submessage);
	*/
	$submessage = preg_replace("/\r\n/",chr(164),$submessage);
	//$submessage = str_replace (chr(163),"\r\n",$submessage);
	//$submessage = str_replace (chr(164),"\r\n",$submessage);
	$submessage = preg_replace("/'/","",$submessage);

	$submessage = preg_replace("/'/","",$submessage);

	$subdep = $_POST["department"];
	$subpir = "2";//$_POST["priority"];
  
	if($subname == ""){
		$error = 1;
		$fontname = "FF0000";
	} else {
		$_SESSION["name"] = $subname;
	}
  
	if($subemail == ""){
		$error = 1;
		$fontemail = "FF0000";
	} else {
		$_SESSION["email"] = $subemail;
	}
	if($subsubject == ""){
		$error = 1;
		$fontsubject = "FF0000";
	} else {
		$_SESSION["subject"] = $subsubject;
	}
	if($subcategories == ""){
		$error = 1;
		$fontcategories = "FF0000";
	} else {
		$_SESSION["categories"] = $subcategories;
	}
	if($submessage == ""){
		$error = 1;
		$fontmessage = "FF0000";
	} else {
		$_SESSION["message"] = $submessage;
	}
	if ($_FILES['upload']['name']) 
	 {
	  	$tmp_name = $_FILES['upload']['tmp_name']; 
   	$new_name = $_FILES['upload']['name']; 

   	$fullpath = $upload_dir;
   	$fullpath = str_replace("..", "", str_replace("\.", "", str_replace("//", "/", $fullpath)));
   	$clean_name = ereg_replace("[^a-z0-9._]", "", str_replace(" ", "_", str_replace("%20", "_", strtolower($new_name) ) ) );
		
		if (!in_array($_FILES['upload']['type'], $upload_ftype))
		 {
			$error = 2;		
         $upload_flag = 0;
//			echo $clean_name."\n";
//			echo $error."\n";		
		 } else { $upload_flag = 1; }
		 
	 }
	 
	/*****************************************/

	$str = "select * from users where email = '".$subemail."'";
		$res =  mssql_query($str) or die(mssql_error());
		$data = mssql_fetch_array($res);

		$i_admin_status  = $data["admin"];
		
		if($i_admin_status == 1 && $_SESSION["admin"] != 1)
		{
			header("location:index.php?x=home&flag=1");
			exit();
		}


/**********************************************/


	$userinfo = mssql_query("SELECT TOP 1 * FROM users WHERE email='".$subemail."'") or die(mssql_error());
	$row = mssql_fetch_array($userinfo);
	$tkey = $row["tkey"];

	if(strtoupper($_POST["tixkey"]) == $tkey){

		
		/*********************************************/
		$_SESSION["tkey"] = $tkey;

		if($error == 1){
			echo "<br><b><font color=\"FF0000\">Error! Invalid fields are in red.</font><b><br>";
		} elseif ($error == 2) {
		   echo "<br><b><font color=\"FF0000\">Error! Upload file must be in Zip format.</font><b><br>";
	   } else
		 {

			echo "<br><b><font color=\"00CC00\">Ticket Submited</font></b><br>";
			$subdate = mktime();
			$subtime = date("H:i:s");
			$i_type = (isSet($_POST['lst_type'])) ? $_POST['lst_type'] : null;
//			$i_type = $_POST["lst_type"];

			//$submessage = preg_replace("/\n/","\n<BR>",$submessage);
			$submessage = $submessage.chr(164)."*".$subemail.", ".date("m/d/Y, g:ia",$subdate).chr(164);
			//$submessage = $submessage."\r\n*".$subemail." ".date("m/d/Y, g:i a",$subdate);
				
			mssql_query("INSERT INTO tickets ( email, subject, categories, message, department, priority, status, date_request, date_assigned, date_closed ) VALUES ( '$subemail' , '$subsubject' , '$subcategories' , '$submessage' , '$subdep' , '$subpir' , '1' , '$subdate' , '' , '' )");

//*** Fetch Maximum Ticket Id From Tickets 
//******
			$q_ticket = "SELECT MAX(ticket_ID) as ticket_ID FROM tickets";
			$res_ticket = mssql_query($q_ticket) or die(mssql_error());
			$data_ticket = mssql_fetch_array($res_ticket);

			$ticketid = $data_ticket['ticket_ID'];
			
			if ($upload_flag == 1) 
			  {
			   
				$tmp_name = $_FILES['upload']['tmp_name'];
				
				$pos_1 = strpos($subemail,"@");
				if($pos_1 != "" && $pos_1 > 0)
				{$upd_email = substr($subemail,0,$pos_1);}
				
				$clean_name = $ticketid."_".$upd_email.".zip";
				
// echo $tmp_name."\n".$fullpath."\n".$clean_name;
				
		      move_uploaded_file($tmp_name, $fullpath . $clean_name); 
 
//				echo "$clean_name of {$_FILES['upload']['size']} bytes was uploaded sucessfully to $fullpath";
				$upd_fname =    $_FILES['upload']['name']; 
				$upd_ftype =    $_FILES['upload']['type']; 
				$upd_fsize =    $_FILES['upload']['size']; 
				$upd_fdate = mktime();
    
//				echo "Name: $name<br />Type: $type<br />Size: $size<br />Tmp: $tmp";
		
		  		mssql_query("INSERT INTO tbl_upload (file_id, file_name, file_size, file_type, upload_date ) VALUES ( '$ticketid', '$upd_fname' , '$upd_fsize' , '$upd_ftype' , '$upd_fdate')");
				
		  		mssql_query("UPDATE tickets SET upload_filename = '".$clean_name."' WHERE ticket_ID='$ticketid'");
		      $subdate = mktime();
				
			  }
		  
		  
/////////////////////////////////////////////////////////////////
		  
			echo "Thank you, ".$subname."!<br>";		
			echo "Your ticket has been submited, you will receive an email confirming your <b> ticket # ".$ticketid."</b><br><BR>";
								
			$userinfo = mssql_query("SELECT TOP 1 * FROM users WHERE email='".$subemail."'") or die(mssql_error());
			$row = mssql_fetch_array($userinfo);
			
			$dbemail = $row["email"];
			
//print("ONE<br>");
			if($dbemail == NULL){

				$emailnew = '1';
			//	print("TWO<br>");

				$tkey = chr(rand(ord("A"), ord("Z"))).chr(rand(ord("A"), ord("Z"))).rand(0,9).rand(0,9).rand(0,9).rand(0,9);
				mssql_query("INSERT INTO users ( name, email, tkey, admin ) VALUES ( '$subname' , '$subemail' , '$tkey' , '0' )");
				echo "Your email is ".$subemail." and your password is ".$tkey." please note this down.<BR><BR>";
			} else {
				//print("THREE<br>");
				$emailnew = '0';
				$tkey = $row["tkey"];
			}
			$_SESSION["tkey"] = $tkey;
			
			//*** Send E-mail
			include("mail.php");
			//***************

			echo "<a href=\"?x=home\">Click here to return to the main page</a><br>";
			
			unset ($_SESSION["subject"]);
			unset ($_SESSION["message"]);
			$subname = "";
			$subemail = "";
			$subsubject = "";
			$submessage = "";
		}
		/*********************************************/

	} else {
		echo "<br><b><font color=\"FF0000\">Error! Invalid password</font><b><br>";
	}
} else {

    $i_hidDept = (isSet($_POST['hidDept'])) ? $_POST['hidDept'] : null;
    echo $i_hidDept;
    
    if (isset($i_hidDept))
      {$_POST["department"] = $i_hidDept;}
	// unset ($_SESSION["categories"]);
	// unset ($_SESSION["message"]);
 // echo "aha aha ".$tmpDept;
}
?>


<form name="frmDept" id="frmDept" method="post" action="">
  <input type="hidden" name="hidDept" id="hidDept" value="<? echo $tmpDept; ?>">
</form>

<form name="frmTicket" method="post" enctype="multipart/form-data">
  <table width="650" border="0" align="center" cellpadding="1" cellspacing="1">
    <tr align="left" valign="top"> 
      <td colspan="2">
		<table width="650" border="0" cellspacing="0" cellpadding="0">
          <tr>
            <td><strong>Submit a support ticket<br>
              </strong><img src="images/submitticket.png" width="54" height="54"></td>
            <td width="45" align="center" valign="top"><a href="index.php?x=home"><img src="images/back.png" width="54" height="54" border="0"><br>
              Back</a></td>
          </tr>
        </table>
      </td>
    </tr>

    <tr align="left" valign="center"> 
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
    
	<tr align="left" valign="center"> 
      <td ><font color="#<? echo $fontname ?>">User Name</font></td>
     <td width="450"> 
        <input name="name" type="text" id="name" value="<?php if(isset($_SESSION["name"])){ echo $_SESSION["name"]; } ?>" disabled maxlength="50">
      </td>
    </tr>
    
	<tr align="left" valign="center"> 
      <td width="130"><font color="#<? echo $fontemail ?>">E-mail</font></td>
      <td> <input name="email" type="text" id="email" value="<?php if(isset($_SESSION["email"])){ echo $_SESSION["email"]; } ?>" maxlength="50"></td>
    </tr>
    
<tr align="left" valign="center"> 
      <td width="130"><font color="#<? echo $fontsubject ?>">Subject</font></td>
      <td><input name="subject" type="text" size="60" id="subject" value="<?php if(isset($_SESSION["subject"])){ echo $_SESSION["subject"]; } ?>" maxlength="120"></td>
    </tr>

    <tr align="left" valign="center"> 
      <td><br><font color="#<? echo $fontdep ?>">Department</font></td>
      <td><br>
<!--	  <select name="department" id="department" onchange="javascript:selDept(this)">  -->
 	  <select name="department" id="department" onchange="javascript:selDept(this)">   
 <?php

echo $_POST['hidDept'];

	$str =  "select * from tbl_departments ";	
	$res = mssql_query($str) or die(mssql_error());
			
/*if($department1 != ""){ echo "<option value=\"1\" selected>$department1</option>"; }
if($department2 != ""){ echo "<option value=\"2\">$department2</option>"; }
if($department3 != ""){ echo "<option value=\"3\">$department3</option>"; }
if($department4 != ""){ echo "<option value=\"4\">$department4</option>"; }
if($department5 != ""){ echo "<option value=\"5\">$department5</option>"; }
*/
?>

<?
echo $_POST['tmpDept'];

			while($data = mssql_fetch_array($res))
			{												
						$tmp_dept = $data["department"];
			?>
<!--					<option value = "<?=$data['id']?>"><?=$tmp_dept?>  -->

 <option value = "<?=$data['id']?>" <?=(isset($_POST['tmpDept']) && $_POST['tmpDept'] == $data['id'] ? "selected=\"selected\"" : "");?>><?=$tmp_dept?>        
					</option>
				<?
					}
				?>
</select></td>

    </tr>   
	<tr align="left" valign="center"> 
      <td width="130">Problem/Request Type</td>
      <td width="600"> 
	  <?php
 //   echo $tmpDept;
    if ($tmpDept <= 0) {$tmpDept = 1;}

//		$str = "select * from tbl_categories order by categories";
    $str = "select * from tbl_categories WHERE dept_id =".$tmpDept."";

    
		$res = mssql_query($str) or die(mssql_error());		
	  ?>
		<select name = "lst_categories">
		<?
			while($data = mssql_fetch_array($res))
			{
				$i_id = $data["id"];
				$s_categ = $data["categories"];
			?>
				<option value = "<?=$s_categ?>"> 
				<?=$s_categ?>
				</option>
			<?
			}
		?>
		</select>
	  </td>
    </tr>
	 
	 	<tr align="left" valign="top"> 
<!--     <td width="130"><font color="#<? echo $fontpir ?>"></font></td> -->
      <td width="200"><font color="#<? echo "1E90FF" ?>"><br>
 File or Screen capture to upload <input type="file" name="upload" /> <br /><i>( only zip file is allowed )</i>
      </font></td>
      </tr>
		
	<tr align="left" valign="top"> 
      <td><font color="#<? echo $fontmessage ?>"><br>Message/Problem</font></td>
      <td> <textarea name="message" cols="60" rows="10" wrap="ON" id="message"><?php if(isset($_SESSION["message"])){ echo $_SESSION["message"]; } ?></textarea></td>
    </tr>
<!--
    <tr align="left" valign="top"> 
      <td><font color="#<? echo $fontdep ?>">Department</font></td>
      <td>
	  <select name="department" id="department">
-->


<?####################################################################################################?>

<?

if(isset($_SESSION["admin"]))
{
   if ($_SESSION["admin"] ==1)
	{	
?>

     <tr align="left" valign="top"> 
      <td><font color="#<? echo $fontpir ?>">Priority</font></td>
      
      <td><select name="priority" id="priority">
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3" selected>3</option>
          <option value="4">4</option>
          <option value="5">5</option>
        </select></td>
     </tr> 
	<?
   }
}
?>
 
	
<?####################m######################################################################################?>	

<!--		
	<tr align="left" valign="center"> 
      <td>Password</td>
      <td><input name="tixkey" type="password" id="tixkey" value="<?php if(isset($_SESSION["tkey"])){ echo $_SESSION["tkey"]; } ?>"></td>
    </tr>
    <tr align="left" valign="top"> 
      <td>&nbsp;</td>
      <td><i>Password is not required if this is your first support ticket.</i></td>
    </tr>
-->    
<br>

    <tr align="left" valign="top"> 
      <td>&nbsp;</td>
      <td><input type="submit" name="Submit" value="Submit"></td>
    </tr>
   
<tr align="left" valign="top">
<td>&nbsp;</td>
</tr>	
  </table>
</form>

Posted: Fri Sep 16, 2005 11:58 am
by ryanlwh
No need to use selected="selected". Correct syntax

Code: Select all

<option value="something" selected>Something</option>
also, i think it's $_POST['department'], not $_POST['tmpDept'], as the drop-down box's name is "department"...

Posted: Fri Sep 16, 2005 12:06 pm
by Burrito
ryanlwh wrote:No need to use selected="selected". Correct syntax

Code: Select all

<option value="something" selected>Something</option>
wrong....

ryanlwh wrote:also, i think it's $_POST['department'], not $_POST['tmpDept'], as the drop-down box's name is "department"...
potentially right....

Posted: Fri Sep 16, 2005 12:19 pm
by ryanlwh
Burrito wrote:
ryanlwh wrote:No need to use selected="selected". Correct syntax

Code: Select all

<option value="something" selected>Something</option>
wrong....
Right out from w3c.org http://www.w3.org/TR/REC-html40/interac ... def-OPTION:

Code: Select all

<!ELEMENT OPTION - O (#PCDATA)         -- selectable choice -->
<!ATTLIST OPTION
  %attrs;                              -- %coreattrs, %i18n, %events --
  selected    (selected)     #IMPLIED
  disabled    (disabled)     #IMPLIED  -- unavailable in this context --
  label       %Text;         #IMPLIED  -- for use in hierarchical menus --
  value       CDATA          #IMPLIED  -- defaults to element content --
  >

 *** example ***

<FORM action="http://somesite.com/prog/component-select" method="post">
   <P>
   <SELECT multiple size="4" name="component-select">
      <OPTION selected value="Component_1_a">Component_1</OPTION>
      <OPTION selected value="Component_1_b">Component_2</OPTION>
      <OPTION>Component_3</OPTION>
      <OPTION>Component_4</OPTION>
      <OPTION>Component_5</OPTION>
      <OPTION>Component_6</OPTION>
      <OPTION>Component_7</OPTION>
   </SELECT>
   <INPUT type="submit" value="Send"><INPUT type="reset">
   </P>
</FORM>
Who's wrong...

Posted: Fri Sep 16, 2005 12:23 pm
by feyd
who's right or not depends solely on what doctype quadoc is using.. ;)

Posted: Fri Sep 16, 2005 12:49 pm
by quadoc
Ok, I changed to post on the "department" and it's work. I should have leave Burrito's code alone instead of changed to "tmpDept". Also, the "selected" works either ways. Thanks for the tips guys... :D

Posted: Mon Sep 19, 2005 1:35 pm
by quadoc
Ok, I got the Drop Down Box to work, but it brought up another interesting thing. Because I've to scroll down to see the whole page, whenever I selected the 1st Drop Down selection, my page looked like it's jumping and the whole page re-display like when I first went into the page. Does anyone know how to stop the page from jumping? Please post some tips. Thanks... 8O

Posted: Mon Sep 19, 2005 1:38 pm
by Burrito
you can use js to capture the y coordinates when you select from the first box, then use the onLoad handler to reposition the page to that coordinate once it's loaded.

Posted: Mon Sep 19, 2005 1:39 pm
by feyd
scrollIntoView() or simply using an anchor (foo.com/page.php#anchor)

Code: Select all

<a name="anchor"></a>

Posted: Mon Sep 19, 2005 2:06 pm
by quadoc
Thanks again for the quick tips guys... By the way, if you guys ever have questions about IBM U2, just let me know :wink: