I'm having a problem with the coding because I cannot get the chosen dropdown menu multi-select Version 1.4.2 to retrieve the previous selected subject value(s) from the dropdown menu when I click it again to activate it.
I'm using two different tables with one field name for each one, so I'm trying to match the t_subjects field name(s) in the member table with the name field name in the category table and if there is a match, that subjects field name will result in <option value='subject_name' selected >subject_name</option> and where there is no match it will be <option value='subject_name'>subject_name</option>
This is what I'm trying to get to happen for those subjects that match when I click it anytime after the first post.
There are forty-two subjects that are dynamically loaded in a chosen multi-select dd menu option.
I have no problem with posting the subject(s) names to the database using the implode method.
if(isset($_POST['submit']))
{
$subjects = implode(',', $_POST['subjects']);
But, if I open the page again to make another post with the subjects field name blank, I get an error that says:
Warning: implode() [function.implode]: Invalid arguments passed in...
So, you can see why I need to have the previous subject(s) values selected when I activate it again. Here is the code for the chosen dd menu.
<tr>
<td width="32%">Subjects:</td>
<td width="68%">
<input type="radio" name="utype" id="sutype" value="s" />Subject(s)
<div id="studspan" style="display:none;">
<strong style="vertical-align:top;">Select Subject(s) :</strong>
<select name="subjects" id="subjects" data-placeholder="Select Subject(s)" style="width:350px;" multiple class="chosen-select">
<?php
$cat_sele = mysql_query("SELECT * FROM category");
while ($cat_row=mysql_fetch_array($cat_sele)) {
if($_POST['subjects'] == $cat_row['name']) $s = " selected"; else $s = "";
echo "<option value='{$cat_row['name']}'$s>{$cat_row['name']}</option>";
}
?>
</select>
</div>
The problem seems to be in this part of the code: if($_POST['subjects'] == $cat_row['name']), because when I replace $_POST['subjects'] with 'Accounting' to check it, it will show that Accounting has been selected when I activate it again, but if I add another subject name, it will show all of the subjects as selected. I even tried if($_POST['t_subjects'] == $cat_row['name']) as well as ("SELECT name FROM category"), but they didn't work either. So any help to help this teacher make it work will be very appreciative.
I have also included other parts of the code that are involved in the process too.
elseif($_SESSION['user_type']=="m")
{
$getuser_sele = "select * from member where member_id = '".$_SESSION['ses_id']."'";
$getuser_qry = mysql_query($getuser_sele);
$getuser_row = mysql_fetch_array($getuser_qry);
$subjects = stripslashes($getuser_row['t_subjects']);
=============================================================
elseif($subjects=="" && $_SESSION['user_type']=="m")
{
$error="Please Enter Preferred Subjects";
}
=============================================================
elseif($_SESSION['user_type']=="m")
{
$qr=mysql_query("update member set
t_subjects='".addslashes($subjects)."',
=============================================================
<body onload="$('.chosen-select').show();
$('.chosen-select').chosen();">
=============================================================
<script type="text/javascript">
$("#sutype").click(function () {
$("#studspan").show(1000);
$('.chosen-select').chosen('destroy');
$('.chosen-select').show();
$('.chosen-select').chosen();
});
</script>
<script src="js/chosen.jquery.js" type="text/javascript"></script>
=============================================================
Update:
Tristan, it works but it shows all of the subject names as selected and de-seleted in the choice list, which is not what I want to happen. I also got the following error in the source code for each of the subject names. I'm just showing the first one below.
<b>Warning</b>: array_search() expects parameter 2 to be array, null given in <b>/home/.../.../edit.php</b> on line <b>2784</b><br /> <option value='Accounting' selected>Accounting</option><br />
I think the problem is how the table/fields are setup in the dbase.
Here is what should happen based upon the first row of the t_subjects. If I log in as member 1 and open the chosen dd menu, Accounting,Athletics,Art from row one of t_subjects should be selected while the rest of the subject list would be non selected in the chosen dd menu. This would happen for each member's row t_subjects they have listed when they initially posted them the first time.
all images to show what I'm talking about.
Using <select name="subjects" ... multiple> will only send post data for one selection. You need to use <select name="subjects[]" ... multiple> to send all selected options in the post data.
Then $_POST['subjects'] will be an array so you will need to search the array for the category name.
$cat_sele = mysql_query("SELECT * FROM category");
while ($cat_row=mysql_fetch_array($cat_sele)) {
if(array_search($cat_row['name'], $_POST['subjects']) !== false) $s = " selected"; else $s = "";
echo "<option value='{$cat_row['name']}'$s>{$cat_row['name']}</option>";
}
Related
This is a bit hard for me to explain and I don't really have any examples to show as I don't know how to do it.
What I am trying to do is to have fields automatically filled up for me based on my selection which is taken from my database.
Let's say I'm trying to fill data up for a casualties form and I'm getting my selection for my fields from a people's database and that database contains all the information of everybody inside, information such as the contact number, next of kin, full name, their IC etc etc.
Is there a way to display data such contact number, next of kin, IC number based on let's say their name inside the form itself?
$query = "SELECT * FROM staff";
$result = mysqli_query($link, $query) or die(mysqli_error($link));
.... in the form itself
<tr>
<td><label><b>Staff ID</b></label></td>
<td><select name="staffID"><option value="">Select staff ID</option>
<?php
while ($row = mysqli_fetch_assoc($result)) {
?>
<option value="<?php echo $row['staff_id']; ?>">
<?php echo $row['staff_id']; ?>
</option>
<?php } ?>
</select></td>
</tr>
The idea is, after they selected an ID from the dropdown box, additional fields will appear, giving the user more details of the staff such as their full name, contact number etc etc.
I can echo out all their ID and I know how to generate out additional fields but I don't know how to auto fill up data on those fields based on the staff_ID they selected.
Sorry if this is confusing, english is not my main language and I'm pretty terrible with programming
English is not my natural language (i`m from brazil).
In this case you will need to use AJAX. The easier way to do that is using Jquery (www.jquery.com). I will put here the easier way, but if cant help, tell me again.
---Let`s go --------------
<option id="reportedBy" name="reportedBy">
<option value="staff" data-name="Full Name of Staff" data-no="(222)2222-2222">
</option>
So you will make a script using jquery. When this option change his value, you will get the selected option value and get the others data using the dataset.
<script>
$(document).ready(function(){
$("#reportedBy").change(function(){
name = $(this).find(":selected").data("name"); //data-name less data-
no = $(this).find(":selected").data("no"); //data-no less data-
//Assuming your textfilds use the id "name" and no
$("#name").val(name);
$("#no").val(no);
});
});
</script>
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.
I'm bug-proofing a form that allows data editing for book entries in a database. Everything is working except for the drop-down box. The drop-down box automatically populates itself with every unique entry in a specific field in the database table, and that part works perfectly. However, when people click to edit a book all the fields are populated with that books information, and I wanted the drop-down box to default to the correct value for that book. My solution was to check each value as it populates the drop-down box against the actual book's value for that field and if they match, make it the "selected" value.
It is not working. The box is still populating fine, but it is not defaulting. Here is the code for the drop-down box.
<span style="margin-left:10px;">
Publication Type:
<select name="publicationType" >
<option value=""></option>
<option value="">-------------------------</option>
<?php
$lPub = '';
if(array_key_exists('publicationType',$_REQUEST)) $lPub = $_REQUEST['publicationType'];
$lPubArr = $datasetManager->getPublicationType();
foreach($lPubArr as $pubStr){
if($pubStr == $bookArr['publicationType']){
echo '<option '.($lPub==$pubStr?'selected="selected"':'').'>'.$pubStr.'</option>'."\n";
}
else{
echo '<option '.($lPub==$pubStr?'':'').'>'.$pubStr.'</option>'."\n";
}
}
?>
</select>
</span>
I can provide what all the variables are if needed. I don't see what I'm doing wrong, but maybe someone will be able to catch an obvious mistake.
Thank you,
Kai
Not sure this will help but try this:
<?php
$lPub = '';
if( array_key_exists('publicationType',$_REQUEST) )
$lPub = $_REQUEST['publicationType'];
$lPubArr = $datasetManager->getPublicationType();
foreach($lPubArr as $pubStr){
echo '<option '.($lPub==$pubStr?'selected="selected"':'').'>'.$pubStr.'</option>'."\n";
}
I removed this condition:
f($pubStr == $bookArr['publicationType'])
since I didn't get what the $bookArr['publicationType'] is used for, perhaps you left it there by mistake
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']; ?>'
I wrote some PHP code that will allow me to create an html dropdown box, and then choose what should be the selected value. The code is:
$role_drop = "<select name='role'>";
$role_drop .= "\r\n<option value='Resident Assistant'>Resident Assistant</option>";
$role_drop .= "\r\n<option value='Community Assistant'>Community Assistant</option>";
$role_drop .= "\r\n<option value='Head RA'>Head RA</option>";
$role_drop .= "\r\n</select>";
$result = mysql_query("SELECT role FROM users");
if (#mysql_num_rows($result)) {
while ($r=#mysql_fetch_assoc($result)) {
$role = $r["role"];
$role_drop = str_replace(">$role</option>", "selected=\"\" >$role</option>",$role_drop);
echo $role_drop;
}
}
In reality, this code has a bunch of HTML mixed in, but here is all of the PHP. When I run it, it seems to work. However, let's say the query returned 4 dropdown boxes with roles (from 4 users), and I were to Edit, or select, a new role for the 2nd dropdown box returned (with an UPDATE query), then when the page refreshes, all of the roles including and AFTER the dropdown box I updated will display their selected values as the new one I selected in the 2nd dropdown box.
And it's not that the values in the actual database are wrong, they are just displaying the wrong selected value. Here is the source code for the 3rd dropdown box after I select a new value for the second one:
<select name="role">
<option selected="" value="Resident Assistant">Resident Assistant</option>
<option value="Community Assistant">Community Assistant</option>
<option selected="" value="Head RA">Head RA</option>
</select>
So, it seems its selecting the correct value (Resident Assistant), however its ALSO selecting "Head RA", which is what I changed the prior dropdown box to.
It's very strange, and I have NO idea why this is happening. Any ideas?
Thanks!
It's because you're updating $role_drop each time, so all the previous changes are going to show up in subsequent dropdowns. I'd change the loop to something like this:
if (#mysql_num_rows($result)) {
while ($r=#mysql_fetch_assoc($result)) {
$role = $r["role"];
$temp_role_drop = str_replace(">$role</option>", "selected=\"\">$role</option>", $role_drop);
echo $temp_role_drop;
}
}
That way you're not overwriting your original dropdown markup.
Nuts - forgot to escape my code. I meant, "It's just <OPTION VALUE="foo" SELECTED>".
Dunno if this helps, but according to the HTML spec you shouldn't be passing a value along with the SELECTED attribute of each OPTION. It's just .