Retrieving value (not display item) of DropDown - php

I am filling DropDown dynamically using AJAX. The DropDown code looks like this:
<select class="element select medium" id="inDistrict" name="inDistrict" onclick="MakeRequest('divDistrict', 'inDistrict', 'SELECT * FROM districtmaster');" onchange="alert(document.getElementByID('inDistrict').value);">
<option value="Select" selected="Select">Select</option>
</select>
Another file that executes on AJAX request contains following code:
<?php
require("dbconnection.php");
require("dbaccess.php");
$dropdownControlName = $_GET['DropDownControlName'];
$query = $_GET['SqlQuery'];
dbconnection::OpenConnection();
$result = dbaccess::GetRows($query);
?>
<select name="<?php echo $dropdownControlName; ?>">
<option>Select from the list</option>
<?php while($row=mysql_fetch_array($result))
{ ?>
<option value="<?= $row[0] ?>"><?= $row[1] ?></option>
<?php } ?>
</select>
Everything works fine and the DropDowns also get filled, except that I am not following how to pick the value of the Option. In the above code you can see that I am using row[0] as value and row[1] as the display item. I want to pick the row[0] value whenever a user selects any row[1] display item.
In the first code above, you can see that I added an onchange event and there is just an alert box. But it is not executing. How to pick the row[0] value and why onchange event is not firing?

onchange doesn't fire in response to DOM manipulation of the selected value. You can fire it manually with some simple javascript:
var inDistrict = document.getElementById('inDistrict');
if (inDistrict.onchange)
inDistrict.onchange();
If you're using jQuery, it's even easier:
$('#inDistrict').change();
Since it looks like you're replacing the entire dropdownlist with your ajax request, just throw some of that javascript in there to fire the change event when it's done populating, and you should be good to go.

Wrong case usage in your onchage event line:
document.getElementByID
Correct:
document.getElementById
Note that rather than using above; you can alert dropdown value like this too:
onchange="alert(this.value);"
Then for dropdown:
If you add [ ] to the names of elements, they become array eg:
<select name="myselect[]">
Now from php you can access each of its element like this:
(assuming that you post method in the form)
echo $_POST['myselect'][0]; // this prints first item value
echo $_POST['myselect'][1]; // this prints second item value
echo $_POST['myselect'][2]; // this prints third item value
//and so on...

Related

How do I store id of items selected from dropdown box inside an array?

I need to store all the items selected from a dropdown box inside array. I have only one form now with the select dropdown list. So each time I select an item from the list and submit the form it overwrites the previous item.
How do I make it work like each time it submits the id will be stored so that I can display all the items selected?
//this is the select dropdown for addon item
<select name="addon">
<?php
mysql_select_db($database_bumi_conn, $bumi_conn);
$query="SELECT * FROM tbl_addons WHERE status=1";
$result=mysql_query($query)or die(mysql_error());
while($row=mysql_fetch_array($result))
{
$a_id=$row['addOns_id'];
$a=$row['addOns'];
?>
<option value="<?php echo $a_id?>"><?php echo $a;?></option>
<?php
}
?>
</select>
//And this is how I store the id
$addon_id=$_POST['addon'];
//edited with session
$_SESSION['option']=array();
$_SESSION['option'][$addon_id]=array('qty'=>$qty,'date_1'=>$date_1,'date_2'=>$date_2);
print_r($_SESSION['option']);
foreach($_SESSION['option'] as $option=>$value)
{
echo $option.'=>';
foreach($value as $val)
{
echo $val;
}
}
You could use SESSION' variables to store all the ID :
session_start();
// Rest of your code here
// $addon_id=$_POST['addon']; Becomes :
if (!in_array($_POST['addon'], $_SESSION['addons']))
$_SESSION['addons'][] = $_POST['addon'];
Edit: Not sure about your edit with sessions. You're resetting $_SESSION['option'] everytime, losing previous addon_id values
Ignoring the fact that you're using a deprecated, inherently un-secure and unmaintained extension, you need to use the multiple attribute on your <select> element and let PHP know that it will be receiving an array of values by using the [] suffix on the element name. To summarise...
<select name="addon[]" multiple>
<?php foreach($collection as $val => $label) : ?>
<option value="<?= htmlspecialchars($val) ?>"><?= htmlspecialchars($label) ?></option>
<?php endforeach ?>
</select>
The PHP variable $_POST['addon'] will then contain an array of selected values (when the form is posted of course).

auto submit dropdown list in php

I want to create a dropdown list in a form and be able to submit/process it without pressing the submit button. I have
$cquery = 'SELECT * FROM tcat ORDER BY id ASC';
$cresult = mysql_query($cquery, $connection);
if(!$cresult){echo 'no result' . mysql_error();}
while($crow = mysql_fetch_array($cresult))
{echo $crow['cat'] . '</option><option>';}
?>
I would like to know if there is a way to make the default that is shown a different value aside the first or the last
even simpler, this should work too!
<select onchange="submit();">
<options ... >
</select>
To submit a form without having the user press a submit button, you can use JavaScript:
document.getElementById("form_id").submit();
To set a default selected option, you can do this:
<option selected="selected">Category Name</option>
Note that PHP will not auto-submit a form for you as it is a server-side language.
You have to use html and javascript and change your script to generate them accordingly:
<select name="aName" onChange="document.getElementById('yourFormId').submit();">
...
</select>

How do I get a drop down/select option have Multiple Values

I've read other questions on here that dealt with what I am looking for. But it still did not help me.
I want to have multiple values in an option of the select tag of a form that will be posting the information onto a different file that is viewable to the visitor by iframe. Example of what I am trying to do:
The following is on the file: Form.php
<div>
<form action"blank.php" method="post" target="box">
<select name="g1">
<option name="g1" value="Value 1, Value 2"> Text </option>
<option name="g1" value="Value 1, Value 2"> Text Blah </option>
</select>
<input type="submit" />
</form>
</div>
<iframe src="blank.php" name="box"></iframe>
The Following is a long the lines of what I want to appear on the: blank.php which is visible by iframe.
Option 1 or 2 value's should appear like this
[ Value 1 ] [ Value 2 ]
An Example:
Its a drop down menu that will post two seperate values when you select one option.
Like if I selected an option that says Hola - hello and it will post:
[Hola] means [Hello].
and the option tag would have the values as:
<option name="g1" value="Hola, Hello">Hola - Hello</option>
Sounds like you want to build an array of your form fields where multiple values are allowed. Read the PHP manual for more.
From the manual:
How do I get all the results from a select multiple HTML tag?
The
select multiple tag in an HTML construct allows users to select
multiple items from a list. These items are then passed to the action
handler for the form. The problem is that they are all passed with the
same widget name. I.e.
<select name="var" multiple="yes">
Each selected option will arrive at the action handler as:
var=option1
var=option2
var=option3
Each option will overwrite the contents of the previous $var variable.
The solution is to use PHP's "array from form element" feature. The
following should be used:
<select name="var[]" multiple="yes">
This tells PHP to treat $var as an array and each assignment of a
value to var[] adds an item to the array. The first item becomes
$var[0], the next $var[1], etc. The count() function can be used to
determine how many options were selected, and the sort() function can
be used to sort the option array if necessary. Note that if you are
using JavaScript the [] on the element name might cause you problems
when you try to refer to the element by name. Use it's numerical form
element ID instead, or enclose the variable name in single quotes and
use that as the index to the elements array, for example:
variable = document.forms[0].elements['var[]'];
First of all, you don't need a name attribute on each of your <option> elements. Just the <select> box.
Second of all, I think all you need is the handy dandy explode function. You'll get the value like this...
$values = $_POST['g1'];
...and then split them into an array like this...
$values = explode(', ', $values);
...and finally just access the values like so:
$value1 = $values[0];
$value2 = $values[1];
I know that this is in the PHP section, but what you are trying to do would be much easier to achieve with javascript. If you change the iframe tags to:
<div id="valueDisplay"></div>
and add an ID and listener to the select
<select name="g1" id="dropDown" onchange="showValues()">
<option name="g1" value="1"> Text </option>
<option name="g1" value="2"> Text Blah </option>
</select>
You just write a little script like this and put it in the body somewhere:
<script type="text/javascript">
function showValues(){
var outDiv = document.getElementById('valueDisplay');
var selectValue = document.getElementById('dropDown').value;
var divText;
if(selectValue == 1) divText = '[ Value 1 ][ Value 2 ]';
if(selectValue == 2) divText = '[ Value 1 ][ Value 2 ]';
outDiv.innerHTML = divText;
}
</script>
To achieve what you are trying to do with iframes would be more difficult. It would require you to use javascript/jquery to post the data within the iframe.
Note that using onchange="" is no longer the accepted method of adding listeners. It is just easier if you are not familiar with javascript.

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']; ?>'

'Remember' form drop list value when submitting to SELF?

I know how to 'remember' some form values whenever submitting the form to itself, in this case because of a picture upload function which requires the form to be submitted to itself. I simply want it so that if the user has filled out all fields and then uploads an image, the form doesn't get resetted (cleared).
I have solved this in regular fields and checkboxes like this:
<input type="text" name="headline" id="headline" value="<?php echo #$_POST['headline'];?>">
But how can I do this with drop lists? or radio buttons? There is no value option in a 'SELECT' list, even though I have tried writing in value anyways in the SELECT statement. Didn't work!
So, how can I set the SELECT (drop down lists) value with PHP (OR JAVASCRIPT) ?
If you need more input let me know, thanks!
For selects, you need to compare each option to your posted value, and handle it individually. Simply print out your options in a loop, and test each value against the value was was previously posted. If it maches, add selected to the attributes of that particular option.
$color = $_POST["colors"];
$colors = array("red","green","blue");
<select name="colors">
<?php foreach ($colors as $option) { ?>
<option<?php print ($option == $color) ? " selected" : ""; ?>>
<?php print $option; ?>
</option>
<?php } ?>
</select>
Actually, found out that it is possible to set the selectedIndex with javascript...
So I could put the selectedIndex in a hidden input before submitting the form, and then get that selectedIndex and set it with a javascript function... tricky but suits me better in this case...
document.getElementById("select").selectedIndex=nr;
Thanks though Jonathan!

Categories