here I have stupid question, hope you can help me.
I create a menu using Select element and option like this:
<option selected="selected">Select type...</option>
<option value="1">Doctor</option>
<option value="2">Patient</option>
and every time I need to pick one value from this menu and use the submit button next to it to transfer data.
But every time the page refreshed, this menu will reveal: Select type...
I want it to reveal the value I chose last time, but don't know how.
Many thanks in advance!!
You'll want to move that selected="selected" onto the selected option.
Doing so in PHP isn't too rough. Just check the $_POST or $_GET (however you sent the form) value for your select box, such as $_POST["selectBox"] for each value down the list. When you find a match, echo out the selected="selected" string there. If the value was empty, output it on your default value.
The easiest way to achieve this is to populate the <select> options in an array, then loop through it to display the <option> list and mark them as selected is the $_POST variable matches the correct value:
<?php $myselect = array(1=>'Doctor', 2=>'Patient'); ?>
<select name="myselect">
<option>Select type...</option>
<?php foreach ($myselect as $value => $label): ?>
<option value="<?php echo $value; ?>"<?php if (isset($_POST['myselect']) && $_POST['myselect'] == $value) echo ' selected'; ?>>
<?php echo $label; ?>
</option>
<?php endforeach; ?>
</select>
<select name="myselect">
<?php
$myselect = array('Select type...','Doctor','Patient');
for($i=0; $i<=2; $i++){
echo "<option value=\"{myselect[$i]}\"";
if (isset($_POST['myselect']) && $_POST['myselect'] == $myselect[$i]){
echo 'selected=\"selected\"';
}
echo ">{$myselect[$i]}</option>";
}
?>
</select>
You have to use the server-side language of you choice to store the selected value in a database, xml or text file.
Edit : I think I may have misunderstood your question.
There are a few ways to do this.
On submit you can save that value as a $_SESSION value and use that to set the select on page load.
Using Javascript you can either set a cookie on change or alter the url to add a parameter (url?selecttype=1) and set that on page load using PHP.
There's a good use of cookies in JS on quirksmode: http://www.quirksmode.org/js/cookies.html
You need to change which one is selected to match the request....
function create_select($properties, $opts)
{
$out="<select ";
foreach ($properties as $propname=>$propval) {
$out.=" $propname='$propval'";
}
$out.=">\n";
foreach ($opts as $val=>$caption) {
$out.="<option value='$value'";
if ($_REQUEST[$properties['name']]==$val) $out.=" SELECTED";
$out.=">$caption</option>\n";
}
$out.="</select>";
return $out;
}
print create_select(array('name'=>'direction',
'id'=>'direction',
'class'=>'colourful',
'onChange'=>''),
array('N'=>'North',
'S'=>'South',
'E'=>'East',
'W'=>'West'));
Related
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).
I've set up a currency conversion dropdown in a wordpress site.
The only thing missing is that every time I load another page, the currency will reset as the form selection was 'forgotten'.
Any ideas how to do this? I tried a suggested js cookie that I saw here, but it doesn't work.
This is what I got so far:
<form name="myform" id ="myform" method="post">
<select name="currency-select" id="sort" onchange="submitform();">
<option value="" selected="selected">Currency</option>
<option value="0">U.S Dollars (USD)</option>
<option value="1">Euros (EUR)</option>
<option value="2">British Pounds (GBP)</option> `
</select>
</form>
js:
function submitform()
{
document.myform.submit();
}
I tried using this code as recommended here but it doesn't really work out for me, I think I didn't do it the right way -
<?php
`session_start();`
if (isset($_POST['currency-select'])) {
$_SESSION['sort'] = $_POST['sort'];
}
?>
I added the $_SESSION to the form as well:
<option value="0" <?php if($_SESSION['sort'] == "0") echo "selected";?>>U.S Dollars (USD)</option>
UPDATE
I've made a few tests. The session seems to be saved (as I echoed it on a few pages while refreshing etc.) I guess the only problem now is related to the form itself. Even with the right session number, I can't get it to select the right option.
I've tried two methods, but both does not work:
<option value="0" <?php if($_SESSION['currency-select'] == "0") echo 'selected="selected"';?>>U.S Dollars (USD)</option>
or
<option value="0" <?php if($_SESSION['currency-select'] == "0") echo "selected";?>>U.S Dollars (USD)</option>
I'd store the selected value in a $_SESSION['selected_currency'] variable and the cross check and select it when the drop down is being populated with the currency list.
Assuming that the sessions are working, I will use something like below to keep the currency selected in your drop down.
<select name="currency">
<?php
foreach($currency as $value){
if($value->currency_code == $_SESSION['currency']){
echo "<option value='$value->currency_code' selected='selected'>$value->currency_name</option>";
} else {
echo "<option value='$value->currency_code'>$value->currency_name</option>";
}
}
?>
</select>
There could be shorter ways, I am using this for illustration purposes.
For permanent retain of data you only have a few possibilities, the easiest to implement are $_SESSION, $_COOKIE or in a Database.
You have two options to do that
1st is by adding a field to the options.php page and save your data then get back your data from the options.php for that you've to use update_option('nameOfField_form','nameOfFieldDb'); and get_option('nameOfFieldDb').
and 2nd option is by jquery.ajax(); method save your data in options.php
you may find these links helpful codex
get_option
update_option
I basically need to create a value by default for a drop down menu on a PHP page that will use the value previously selected and stored in the database.
For example, lets just say I have the value '3' stored in a database column. I want to use this number as the default value for a drop down menu where the <option value = "3">Good</option>. Is there a simple solution to this problem?
Or do i literally need to loop through the values until it makes a value?
Thanks.
I usually do this
<?php
$sel = 'selected="selected"';
$current_whatever = 5;
?>
<option name="whatever">
<?php foreach($list as $listItem): ?>
<option value="<?=$listItem->id?>" <?=($listItem->id == $current_whatever)?$sel:''?>><?=$listItem->name?></option>
<?php endforeach; ?>
</option>
I'm using an inline if statement to check each one :) Looks reasonably tidy.
Assuming you're using database objects, you get the idea if you're not though :)
<?php foreach($options as $key=>$option){?>
<option value='<?=$key?>' <? echo $key==$selected?"SELECTED":"";?> ><?=$option?></option>
<? }?>
If I have a line like this,
<option value="someval">somval</option>
how can I position the cursor after the last quotation of value and put something like abcdef?
So the output would be
<option value="somval" abcdef>somval</option>
with PHP?
I want to do this dynamically and I can't figure out how to do it. I'm looking at strpos(), but I don't see how it can be done. I'll be posting a bunch of option tags into a textbox and code will be generated. so I'll have a lot of option fields.
#martin - Say I have a huge dropdown and each option lists a country that exists. Rather than having to manually type out something like this:
$query = $db->query("my query....");
while($row = $db->fetch($query)) {
<select name="thename">
<option value="someval" <?php if($row['someval'] == 'someval') { print "selected"; } ?> >someval</option>
<option value="someval" <?php if($row['someval'] == 'someval') { print "selected"; } ?> >someval</option>
<option value="someval" <?php if($row['someval'] == 'someval') { print "selected"; } ?> >someval</option>
... Followed by 100 more, because there are a lot of locations to list.
</select>
How can I post all the options I have into a textbox and have the above code automatically generated to save a lot of time?
Using your example you would do:
while($row = $db->fetch($query)) {
printf('<option value="someval"%s>someval</option>',
($row['someval'] == 'someval') ? ' selected="selected" ' : '');
}
This would go through the rows and output an option, replacing the %s with the attribute selected="selected" if $row['someval'] is equal to someval. However, the above is rather pointless, because all option elements will have the same value and text, so try
while($row = $db->fetch($query)) {
printf('<option value="%s"%s>%s</option>',
$row['country-code'],
($row['country-code'] === $selection) ? ' selected="selected" ' : '',
row['country-name']);
}
With $selection being anything you want to compare against. Replace the keys in $row with appropriate keys from in your database.
Note: The usual disclaimers about securing your output apply
You could capture (value=".+?") and replace it with $0 abcdef.
<?php
$string = '<option value="someval">someval</option>';
print preg_replace("/(value=\".+?\")/i", "$0 abcdef", $string);
?>
Which outputs the following:
<option value="someval" abcdef>someval</option>
With PHP, you can generate a whole string with any text you wish. Where do you have your original string? In a variable or a text file?
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!