PHP/HTML: Creating A SubMenu - php

I have this filtering feature on my program. It is in the form of a drop-down list. I'm currently using the Select-Option method to display the options on my dropdown list. However, it doesn't look good if the list is very long so what I would want to do is create a submenu. For example, I have 20 options. What I want is to transform it into 5 options with each option also having children or sub-options.
Here's what I did originally and could be a good case. So instead of displaying the 3 malls under the main options, I would want to make a mother option called "Filter by Mall" then later on, "Filter by Location" instead of displaying all locations on the main option, etc.
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="GET">
<select name="formStats">
<option value="Rob">Robinson's Manila Stores</option>
<option value="MoA">Mall of Asia Stores</option>
<option value="GG">Greenbelt/Glorietta Stores</option>
<input type="submit" name="formSubmit" value="Submit"/>
</form>
Here's the part where I put the cases under my PHP script.
if(isset($_GET['formSubmit']))
{
$varStats = $_GET['formStats'];
$errorMessage = "";
switch($varStats)
{
case "Rob": $show = "Mall = 'Robinson\'s Manila'"; break;
case "MoA": $show = "Mall = 'Mall of Asia;"; break;
case "GG": $show = "Mall = 'Glorietta/Greenbelt'"; break;
}
$conn = db_connect();
showStore($conn, $show);
db_disconnect($conn);
exit();
}

On the issue of hovering over the option element this note from MDN might be of interest.
[2] Historically, Firefox has allowed keyboard and mouse events to
bubble up from the element to the parent element.
This doesn't happen in Chrome, however, although this behavior is
inconsistent across many browsers. For better Web compatibility (and
for technical reasons), when Firefox is in multi-process mode and the
element is displayed as a drop-down list. The behavior is
unchanged if the is presented inline and it has either the
multiple attribute defined or a size attribute set to more than 1.
Rather than watching elements for events, you should watch
for {event("change")}} events on
I experimented with nested selects - doesn't work. Listening for events on the option element also did not work ( at least not in Chrome which is what I use most these days, hence note above ) so you MIGHT be able to monitor events on the parent (select) and accomplish what you want that way - no doubt there is sometrickery available in jQuery to do this...
As an aside, a little experiment - not exactly what you were trying to do but close.
<select id='depsel'>
<option data-menu=1>1st Example
<option data-menu=2>2nd Example
<option data-menu=3>3rd Example
</select>
<span id='subopt' style='display:none;border:1px solid black;width:100px;min-height:200px;'></span>
<script>
var menu=document.getElementById('depsel');
var span=document.getElementById('subopt');
menu.addEventListener('change',function(e){
var selected=this.options[this.options.selectedIndex].dataset.menu;
span.style.display='block';
span.innerHTML='';
var div=document.createElement('div');
div.innerHTML=this.value;
div.onclick=function(evt){
span.style.display='none';
}
span.appendChild( div );
}.bind( menu ),false );
</script>

Related

HTML Dropdown menu with autosuggestion and auto updation

I am trying to develop a webpage based on html, css. I am using PHP for server side scripting.
I want a dropdown menu to be displayed with available options, But at the same time I need this drop down list to accept text. so I can choose from dropdown list as well from the text box whatever I want.
I found one solution for the above scenario and working fine, but what extra I want that, once I write something in the text box, which is not an options of the dropdown, from the next time it will auto include it.
e.g. ->
currently my dropdown is having say three options "Samsung", "Sony", "Apple"
<option value="one">Samsung</option>
<option value="two">Sony</option>
<option value="three">Apple</option>
Now, "Lenevo" is not available. For the First time in the text box I will write "Lenevo" as my choice, there after it will include it into the dropdown menu.
<option value="one">Samsung</option>
<option value="two">Sony</option>
<option value="three">Apple</option>
<option value="four">Lenevo</option>
.
.
Like that it will happen.
Thanks for help.. :)
The best solution would be something like select2. (JavaScript)
For examples look here: Link
If you want to stay with PHP only, you need to offer a from to submit text values:
(Disclaimer: This solution is quite bad practice. But it's an example on how to solve it, on a low level.)
1) offer a form
<input type="text" name="addSelection">
2) Read post request
$newOption = $_POST["addSelection"];
3) Persist new option somewhere (here Session, also possible are databases)
$_SESSION["additionalOptions"][] = $newOption;
4) Merge with standard options
$options = ["apple","banana"];
$options = array_merge($options,$_SESSION["additionalOptions"]);
5) Create Options in HTML
<select name="fruits">
<?php
foreach($options as $option){
echo '<option value="'+$option+'">'+$option+'</option>';
}
?>
</select>
Use select2 plugin
https://github.com/select2/select2
<script type="text/javascript" src="/assets/profile/js/select2.min.fda43621.js"></script>
var validateTag = function (term, data) {
var value = term.term;
var re = /^[a-z\d\-_\s]+$/i;
if (re.test(value))) {
return {
id: value,
text: value
};
}
return 'wrong_characters';
};
$("#selectAlt").select2({tags: true, maximumSelectionLength: 6, maximumInputLength: 20, createTag: validateTag});
HTML:
<select name="selectAlt[]" id="selectAlt" multiple="multiple" custom-placeholder="Genre">
<option value="Blues">Blues</option>
<option value="Classic Rock">Classic Rock</option>
<option value="Country">Country</option>
</select>

Changing options in second drop down menu by user input in first drop down menu

Thanks for taking time to look at this.
I have two drop down menus. The first is a list of clients, the second is a list of projects.
All projects are tied to just one client, so I'd like for the code to get user input for the client, then read that value, and modify the PHP code to only print out the values in the second drop down menu that correspond to the client selected.
Here's some code. For the first drop down menu:
<div class="item">
<label for='clSel' id='tsClLabel'>Client:</label>
<select name='clSel' id='wClient' onChange="bGroup();">
<option></option>
<?php
$cQuery = "SELECT * FROM Clients ORDER BY Client_Name";
$cResult = mysql_query($cQuery);
while($cData = mysql_fetch_assoc($cResult)) {
echo '<option id="Cid" value="'.$cData['Id'].'">'.$cData['Client_Name'].'</option>';
}
?>
</select>
Here's my jQuery function to get the user-selected value from the first drop down:
<script>
function bGroup(){
val1 = $("#wClient").val();
// window.alert(val1);
// $('#div1').html(val1);
return val1;
}
</script>
And the code for the second drop down menu:
<label for='billGroupId'>Billing Group: </label>
<select name='billGroupId'>
<option value=''></option>
<?php
$sql = "SELECT * FROM Billing_Groups ORDER BY Client_Id, Name";
$sth=$dbh->prepare($sql);
$sth->execute();
while ($row = $sth->fetch())
{
if ($row['Name']!= ''){
echo "<option value='".$row['Id']."' > ".$row['Name']."</option>";
echo "<script> bGroup(); </script>"
}
}
?>
</select>
I know I need to include a WHERE statement in the second drop down menu
Basically Select * FROM Clients WHERE Client_ID == $jsVAR.
I already have the value I need in the var1 JavaScript variable. How can I get this little piece of data either read by PHP or sent to PHP via JS code?
Thanks!!
You can SELECT all records from the database, and then insert them to your page HTML using json_encode(). Something like that:
<?php
$sql = "SELECT * FROM Billing_Groups ORDER BY Client_Id, Name";
$sth=$dbh->prepare($sql);
$sth->execute();
$projectData = array();
while ($row = $sth->fetch())
{
if ($row['Name']!= ''){
$projectData[$row['Client_Id']][] = $row;
}
}
echo '<script type="text/javascript">var projects=', json_encode($projectData), ';</script>';
?>
Then, in your JS, you use the variable projects as an associative array (object), eg.:
<script type="text/javascript">
for (p in projects[clientId]) {
alert(projects[p].Name);
}
</script>
Tricky one,
You have a choice. One way is to use Ajax to grab the second level menu structure upon getting the first level choice, and populate the second level once that succeeds. That's likely to be a problem, as there will likely be some sort of network delay while that happens, of which you have no control (unless you are in a closed environment). So from a user point of view it could be counter intuitive and sluggish feeling, especially on a slow connection or shared hosting solution where timings can vary enormously.
The other way is to somehow pull all values possible and filter them (so hide the ones that don't apply) using jQuery, perhaps utilising classes or some other attribute as a method of filtering data. Using jQuery you can assign data to elements so you could also use that too. The second method may not be so good if there's a lot of data (can't tell from the scenario you've described). Looking at your second level code I don't see a WHERE condition so I'm not sure how the value from the first level is affecting that of the second level, so it's hard to know how to deal with that for this method.

Have data in mySQL database be reflective of what's displayed in a drop down menu.

Thanking you for taking the time to look at this question.
The premise of the situation is that I have a "website" written in PHP and HTML that displays items from my database named "Spreadsheet." There are six columns, and over 4000+ rows of data. The columns are "accountID", "accountName", "website", "rating", "imageURL", "comments." The column "rating" in the website is a drop down list.
Currently, everything works well, but I have do questions:
How do I, with PHP, have data submitted to the database upon clicking on an option (such as "Very Bad") in the drop down list? At the moment, it requires the user to click a "submit" button, which refreshes the page entirely, losing their position. Is it possible to have it submit silently (without refreshing)
Second question has to do with the drop-down list again. How do you have the drop-down list display what's in the database? For example, if rating is "Very Bad" in the database, the drop-down list reflects that, and not what the first element is.
Below is my code.
". $row['website']."<br />
<Form Name =\"rating\" Method =\"POST\" ACTION =\"\" />
<input type = \"hidden\" name=accountID value=" . $row['accountID'] . ">
<select name=\"rating\">
<option value=\"\"></option>
<option value=\"Very Bad\">Very Bad</option>
<option value=\"Bad\">Bad</option>
<option value=\"Average\">Average</option>
<option value=\"Above Average\">Above Average</option>
</select>
<INPUT TYPE =\"Submit\" Name =\"formSubmit\" VALUE =\"Submit\">
if (isset($_POST['formSubmit'])){
$rating = $_POST['rating'];
$accountID = $_POST['accountID'];
var_dump($rating);
var_dump($accountID);
if(!mysql_query("UPDATE Spreadsheet SET rating='$rating' WHERE accountID='$accountID'")) {echo 1;}
}
mysql_close();
?>
Thanks so much! This question has been bothering me for a bit. I have tried many Google attempts, but I could not find an answer as specific as I am asking. Thank you so much.
Answer to #1:
You can use Javascript/AJAX to accomplish submitting the form without actually pressing submit. There are various javascript libraries that can help you accomplish this a lot easier than bare bones Javascript, namely jQuery ( http://jquery.com/ ). It's not a very complicated task but you will need to learn some basic Javascript and how to use jQuery. The essential flow of things would be when the form changes, submit an AJAX request to submit the form. You will need a second script to take the incoming AJAX request and do the save. Try search engines for some basic jQuery tutorials, and once you have a basic grip, something like "ajax submit on form change jquery" will get you started.
Answer to #2:
Something like this (please see my notes...)
echo '<select name="rating" id="rating">';
$q = mysql_query("SELECT `option_name` FROM `options`");
while($row = mysql_fetch_assoc($q)) {
echo '<option value="' . $row['option_name'] . '">' . $row['option_name'] . '</option>';
}
echo '</select>';
If you would like the select preselected, that's pretty easy too! Taking from the last example:
$pre_selected = "Very Bad";
echo '<select name="rating" id="rating">';
$q = mysql_query("SELECT `option_name` FROM `options`");
while($row = mysql_fetch_assoc($q)) {
echo '<option value="' . $row['option_name'] . '"';
if($row['option_name'] == $pre_selected) {
echo ' selected="selected"';
}
echo '>' . $row['option_name'] . '</option>';
}
echo '</select>';
But this is the part I'd like to point a few things out:
Don't use the old mySQL library like you are using and my examples are using. Please, use PDO, or at least mySQLi. The functions you are using are deprecated, and may not be available in PHP for much longer.
Please, escape your data properly. Search for "SQL Injection" and you will find a massive amount of information about how your code is very insecure (your UPDATE, specifically) because you did not escape the values.
Just a heads up, when/if you use jQuery, you're going to need to use id="foo" in addition to name="foo".
For the first question you can look at ajax onchange event. Basically when you change select value you fill call function that can call php file to insert data in db.
For the second question you check the DB for selected value and if it matches option value or text you set it to selected
<select name=\"rating\">
<option value=\"\"></option>
<option value=\"Very Bad\">Very Bad</option>
<option value=\"Bad\">Bad</option>
<option value=\"Average\">Average</option>
<option value=\"Above Average\"
<?php if($someValueFromDb=='Above Average'){
echo 'selected=selected';}?>
>Above Average</option>
</select>

onChange refresh particular dropdown list in PHP

THE ISSUE?
I need help regarding PHP's onChange command. Basically i'm making a hotel room reservation system. What im trying to do is that there are tow combo boxes.
One for HOTEL NAME (COMBO BOX NO.1)
the other for FLOOR NO (COMBO BOX NO.2)
What I want to do is that if I select the hotel name form the combo box 1, then the number of floors for that particular hotel, should get auto-populated in combo box 2. (This number of floors information should come from the respective table/field in the database)
WHAT i'VE TRIED TO DO -- THE CODE
<td>Hotel:
<select name="hotel_name" id="hotel_name" title="<?php echo $row_rs_hotel['hotel_name']; ?>" onchange="<?php
while ($row_rs_floor = mysql_fetch_assoc($rs_floor));
$rows = mysql_num_rows($rs_floor);
if($rows > 0) {
mysql_data_seek($rs_floor, 0);
$row_rs_floor = mysql_fetch_assoc($rs_floor);
}
?>">
<?php
do {
?>
<option value="<?php echo $row_rs_hotel['hotel_name']?>"><?php echo $row_rs_hotel['hotel_name']?></option>
<?php
} while ($row_rs_hotel = mysql_fetch_assoc($rs_hotel));
$rows = mysql_num_rows($rs_hotel);
if($rows > 0) {
mysql_data_seek($rs_hotel, 0);
$row_rs_hotel = mysql_fetch_assoc($rs_hotel);
}
?>
</select></td>
</tr>
<tr>
<td>Floor No:
<select name="floor_no" id="floor_no" title="<?php echo $row_rs_floor['floor_no']; ?>" onchange="var id=$('hotels_name').val();
$('floors_no').load('ajax.php?id='+id);
">
<?php
do {
?>
<option value="<?php echo $row_rs_floor['floor_no']?>"><?php echo enter code here$row_rs_floor['floor_no']?></option>
<?php
} while ($row_rs_floor = mysql_fetch_assoc($rs_floor));
$rows = mysql_num_rows($rs_floor);
if($rows > 0) {
mysql_data_seek($rs_floor, 0);
$row_rs_floor = mysql_fetch_assoc($rs_floor);
}
?>
</select></td>
WHAT I'M GETTING FROM THE ABOVE CODE??
The combo box number 2 is auto-loaded with the first record in the table when the page is opened. No matter how many times i select the hotel in COMBO BOX 1, the values in combo box 2 remain unchanged.
PLEASE HELP..!!!
You must combine both javascript and php, as you want to retrieve the information from the database (server side using php+a bit of mysql) with a dynamic page without refresh (client side using javascript). It will certainly become a long difficult job, but I think it's the best approach.
Read this article about double drop down menu and study the code this article (or search for similar projects) and when you understand the javascript, you must fill it where it's appropriate with php.
For example, this is a bit of the javascript (or html) source code:
if (Indx==1)
{
options[0]=new Option("Choose a JavaScript Page","");
options[1]=new Option("Alerts","alerts.htm");
options[2]=new Option("Back and Forward Buttons","BackForward.htm");
options[3]=new Option("Contents","index.html");
}
For your project it should be something like this (not complete and not bug-free, but it's just to give you an idea:
if (Indx==1)
{
<?php
$i=0;
while ($row = mysql_fetch_array($result))
{
?>
options[<?php echo $i;?>]=new Option("<?php echo $row['name']."\",\"".$row['page']; ?>");
<?php $i=$i+1; } ?>
}
That should give you the same code (assuming that 'name' and 'page' are values of your columns in your database). And that needs to be done in all convenient javascript bits, but I won't do all your work... give it your best and, if it still doesn't work, come back and ask a more specific question about the code.
If you make it work, I'd like to encourage you to post it here editing your question so everyone can learn from it. Keep in mind that this is how I would approach this problem, but there are surely other ways of doing it.

Two drop down list values auto selected based on php session value

I have two drop down lists.
Second one is populated based on value chosen in the first one. I'm using Double Combo Script Credit By JavaScript Kit to do that (I am very bad with javascript).
I use this to filter results from my Mysql database.
The problem is that when user applies filter i want him to see what he applied (when page refreshes or user goes to other page) - those values should be seen as selected in both drop down lists. I can't figure out where i should place an event or something else.
I'm holding subcategory values from the second drop down list in php session :
if (isset($_SESSION['subcat']) && !isset($_GET['subcat'])){
$color= $_SESSION['subcat'];
}
elseif (!isset($_SESSION['subcat']) && isset($_GET['subcat']))
{
$_SESSION['subcat'] = mysql_real_escape_string($_GET['subcat']);
$color= $_SESSION['subcat'];
}
elseif (isset($_SESSION['subcat']) && isset($_GET['subcat'])){
unset($_SESSION['subcat']);
$_SESSION['subcat'] = mysql_real_escape_string($_GET['subcat']);
$color= $_SESSION['subcat'];
}
else {
$color= "";
};
I can echo selected in first drop down list, based on session value and that works, but a second one drop down list is not generated when page refreshes and i don't know where should i echo 'selected = "selected"' or maybe everything can be done only with javascript? Please help.
The code:
<div class="filter">
<form method="get" name="doublecombo" action="" id="filterform" >
<select name="example" id="exampl" size="1" onChange="redirect(this.options.selectedIndex)">
<option>All kinds</option>
<option>Women</option>
<option>Men</option>
</select>
<select name="subcat" size="1" id="subcategory">
<option value="lists.php">All colors</option>
</select>
<input type="button" name="test" value="Filter" onClick="go()">
</p>
<script>
<!--
/*
Double Combo Script Credit
By JavaScript Kit (www.javascriptkit.com)
Over 200+ free JavaScripts here!
*/
var groups=document.doublecombo.example.options.length
var group=new Array(groups)
for (i=0; i<groups; i++)
group[i]=new Array()
group[0][0]=new Option("All colors","list.php")
group[1][0]=new Option("Pink","list.php?subcat=1 ")
group[1][1]=new Option("White","list.php?subcat=2")
group[1][2]=new Option("Green","list.php?subcat=3")
group[2][0]=new Option("Black","list.php?subcat=12")
group[2][1]=new Option("Blue","list.php?subcat=13")
group[2][2]=new Option("Grey","list.php?subcat=14")
group[2][3]=new Option("Brown","list.php?subcat=15")
var temp=document.doublecombo.subcat
function redirect(x){
for (m=temp.options.length-1;m>0;m--)
temp.options[m]=null
for (i=0;i<group[x].length;i++){
temp.options[i]=new Option(group[x][i].text,group[x][i].value)
}
temp.options[0].selected=true
}
function go(){
location=temp.options[temp.selectedIndex].value
}
//-->
</script>
</form></div>
you could set a cookie to hold the selected value, so if the user selects there choice and refreshes, you would then check if the cookie exists and then populate the menus accordingly.
Update:
This will store the selected values and repopulate the select menus if the user refreshes the page.
First select added onkeup:
<select name="example" id="exampl" size="1" onchange="redirect(this.options.selectedIndex)" onkeyup="redirect(this.options.selectedIndex)">
for the second select and as follows to check for changes
<select name="subcat" size="1" id="subcategory" onchange="checks(this)" onkeyup="checks(this)">
Now find the Line temp.options[0].selected=true and add this directaly below
createCookie("selected_option_1", x, 0);
if(x==0){
eraseCookie("selected_option_2");
}
then add these two new function say at the bottom of your script block
// checks if the Second Select has changed
function checks(oWhich){
createCookie("selected_option_2", oWhich.selectedIndex, 0);
}
// repopulate the options base on selection thats saved in the cookies
onload = function(){
if(readCookie("selected_option_1") != null) {
redirect(document.doublecombo.example.options.selectedIndex = readCookie("selected_option_1"));
if(readCookie("selected_option_2") != null) {
document.doublecombo.subcat.options.selectedIndex = readCookie("selected_option_2");
}
}
}
Finaly for these functions/scrip to work you will need
// The cookie script im using for the functions is located below include this and you chould ok. http://www.quirksmode.org/js/cookies.html#script
Now once the form has been submitted you GET the selected values as usual, and the REPOPULATE the menu, once you done with the cookie you could remove them.
If it's jQuery you are using you can try a short PHP tag on the page like this:
jQuery('#MyDropDown').val('<?php echo $_SESSION['MyStoredValue']; ?>');
If you are not using jQuery but straight JavaScript this would have the same effect:
document.getElementById("MyDropDown").value = '<?php echo $_SESSION['MyStoredValue']; ?>'

Categories