Selecting a select list based on post request - php

please, i'm somewhat new with php bear with me.
I have a selectbox...
<select name="criteria">
<option value="1">Student ID</option>
<option value="2">Firstname </option>
<option value="3">Lastname</option>
<option value="6">All</option>
</select>
<input name="searchvalue" type="text">
<input name="search" type="submit" value="Search">
When i search with a particular option, after the post request, the selected option usually defaults to Student ID. But i want it to still remain the option i searched with. Any suggestion would be appreciated.

To be honest I'd adjust your select code just a little bit to allow for a bit more dynamic editing..
<?php
$options = array('1'=>'Student ID', '2'=>'Firstname', '3'=>'Lastname', '6'=>'All');
?>
<select name="criteria">
<?php
foreach($options as $key=>$value){
$addtItem = '';
if(isset($_POST['criteria']) && $_POST['criteria']==$key){
$addtItem = 'selected="selected"';
}
echo('<option '.addtItem.' value="'.key.'">'.$value.'</option>');
}
?>
</select>
This way you can quickly add more values without a ton of repeat code..

<select name="criteria">
<option value="1" <?php if ($_POST["criteria"] == 1) echo "SELECTED"; ?>>Student ID</option>
<option value="2" <?php if ($_POST["criteria"] == 2) echo "SELECTED"; ?>>Firstname </option>
<option value="3" <?php if ($_POST["criteria"] == 3) echo "SELECTED"; ?>>Lastname</option>
<option value="6" <?php if ($_POST["criteria"] == 6) echo "SELECTED"; ?>>All</option>
</select>
Really ugly, but that works.

You need to check the $_POST array and select the corresponding select item
<?php
$criteria = isset($_POST['criteria']) ? $_POST['criteria']: 0;
?>
<select name="criteria">
<option value="1" <?php echo ($criteria == '1') ? 'selected="selected"': ''; ?>>Student ID</option>
<option value="2" <?php echo ($criteria == '2') ? 'selected="selected"': ''; ?>>Firstname </option>
<option value="3" <?php echo ($criteria == '3') ? 'selected="selected"': ''; ?>>Lastname</option>
<option value="6" <?php echo ($criteria == '6') ? 'selected="selected"': ''; ?>>All</option>
</select>

Related

How to use a php variable as a value in a select tag? [duplicate]

Is there any way to set the selected item in a drop down box using the following 'type' code?
<select selected="<?php print($row[month]); ?>"><option value="Janurary">January</option><option value="February">February</option><option value="March">March</option><option value="April">April</option></select>
The database holds a month.. and I want to allow on the edit page, them to choose this month.. but it to be pre-filled with their current setting?
You need to set the selected attribute of the correct option tag:
<option value="January" selected="selected">January</option>
Your PHP would look something like this:
<option value="January"<?=$row['month'] == 'January' ? ' selected="selected"' : '';?>>January</option>
I usually find it neater to create an array of values and loop through that to create a dropdown.
You mark the selected item on the <option> tag, not the <select> tag.
So your code should read something like this:
<select>
<option value="January"<?php if ($row[month] == 'January') echo ' selected="selected"'; ?>>January</option>
<option value="February"<?php if ($row[month] == 'February') echo ' selected="selected"'; ?>>February</option>
...
...
<option value="December"<?php if ($row[month] == 'December') echo ' selected="selected"'; ?>>December</option>
</select>
You can make this less repetitive by putting all the month names in an array and using a basic foreach over them.
You can use this method if you use a MySQL database:
include('sql_connect.php');
$result = mysql_query("SELECT * FROM users WHERE `id`!='".$user_id."'");
while ($row = mysql_fetch_array($result))
{
if ($_GET['to'] == $row['id'])
{
$selected = 'selected="selected"';
}
else
{
$selected = '';
}
echo('<option value="'.$row['id'].' '.$selected.'">'.$row['username'].' ('.$row['fname'].' '.substr($row['lname'],0,1).'.)</option>');
}
mysql_close($con);
It will compare if the user in $_GET['to'] is the same as $row['id'] in table, if yes, the $selected will be created. This was for a private messaging system...
Simple and easy to understand example by using ternary operators to set selected value in php
<?php $plan = array('1' => 'Green','2'=>'Red' ); ?>
<select class="form-control" title="Choose Plan">
<?php foreach ($plan as $id=> $value) { ?>
<option value="<?php echo $id;?>" <?php echo ($id== '2') ? ' selected="selected"' : '';?>><?php echo $value;?></option>
<?php } ?>
</select>
Its too old but I have to add my way as well :) because it is generic and useful especially when you are using static dropdown values.
function selectdCheck($value1,$value2)
{
if ($value1 == $value2)
{
echo 'selected="selected"';
} else
{
echo '';
}
return;
}
and in you dropdown options you can use this function like this and you can use this as many as you can because it fits with all of your select boxes/dropdowns
<option <?php selectdCheck($row[month],january); ?> value="january">january</option>
:) I hope this function help others
Simple way
<select class ="dropdownstyle" name="category" selected="<?php print($messageeditdetails[0]['category_id']); ?>">
<option value=""><?php echo "Select"; ?></option>
<?php foreach ($dropdowndetails as $dropdowndetails) { ?>
<option <?php if($messageeditdetails[0]['category_id'] == $dropdowndetails['id']) { ?> selected="<?php echo $dropdowndetails['id']; ?>" <?php } ?> value="<?php echo $dropdowndetails['id']; ?>"><?php echo $dropdowndetails['category_name']; ?></option>
<?php } ?>
</select>
This is the solution that I came up with...
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<select name="select_month">
<?php
if (isset($_POST['select_month'])) {
if($_POST["select_month"] == "January"){
echo '<option value="January" selected="selected">January</option><option value="February">February</option>';
}
elseif($_POST["select_month"] == "February"){
echo '<option value="January">January</option><option value="February" selected="selected">February</option>';
}
}
else{
echo '<option value="January">January</option><option value="February">February</option>';
}
?>
</select>
<input name="submit_button" type="submit" value="Search Month">
</form>
A Simple Solution:
It work's for me
<div class="form-group">
<label for="mcategory">Select Category</label>
<select class="form-control" id="mcategory" name="mcategory" required>
<option value="">Please select category</option>
<?php foreach ($result_cat as $result): ?>
<option value="<?php echo $result['name'];?>"<?php
if($result['name']==$mcategory){
echo 'selected';
} ?>><?php echo $result['name']; ?></option>
}
<?php endforeach; ?>
</select>
</div>
Check this:
<select class="form-control" id="department" name="department" type="text">
<option value="medical-furniture" #if($list->department == "medical-furniture") selected #endif>Medical furniture</option>
<option value="medical-table" #if($list->department == "medical-table") selected #endif>Medical table</option>
<option value="service" #if($list->department == "service") selected #endif>Service</option>
</select>
My suggestion is to leverage the hidden/collapse attribute. Try with this example:
<select>
<option value="echo $row[month]" selected disabled hidden><? echo $row[month] ?></option>
<option value="1">Jan</option>
<option value="2">Feb</option>
<option value="3">Mar</option>
</select>
in case of null for $row[month] the selected item is blank and with data, it would contain less codes for many options and always working for HTML5 and bootstrap etc...
If you have a big drop down. it's much easier to use jQuery with PHP.
This is how to do it:
<script>
$(document).ready(function () {
$('select[name="country"]').val('<?=$data[0]['Country']?>');
});
</script>
The easiest solution for the selected option in dropdown using PHP is following
<select class="form-control" name="currency_selling" required >
<option value="">Select Currency</option>
<option value="pkr" <?=$selected_currency == 'pkr' ? ' selected="selected"' : '';?> >PKR</option>
<option value="dollar" <?=$selected_currency == 'dollar' ? ' selected="selected"' : '';?> >USD</option>
<option value="pounds" <?=$selected_currency == 'pounds' ? ' selected="selected"' : '';?> >POUNDS</option>
<option value="dirham" <?=$selected_currency == 'dirham' ? ' selected="selected"' : '';?> >DRHM</option>
</select>
You can try this after select tag:
<option value="yes" selected>yes</option>
<option value="no">no</option>

How to select more option in a dropdown with array of value using php?

How to select a multiple choices of array in a dropdown using php.
Input :
<?php
$val = "22,33,55";
?>
<select name="choice" multiple="true">
<option value="11">11</option>
<option value="22">22</option>
<option value="33">33</option>
<option value="44">44</option>
<option value="55">55</option>
</select>
I want the Output like:
<select name="choice" multiple="true">
<option value="11">11</option>
**<option value="22">22</option>**
**<option value="33">33</option>**
<option value="44">44</option>
**<option value="55">55</option>**
</select>
<?php
$val = "22,33,55";
$valarray = explode(',',$val);
?>
<select name="choice" multiple="true">
<option value="11" >11</option>
**<option value="22" <?php if(in_array(22,$valarray)){ ?>selected="selected"<?php } ?>>22</option>**
**<option value="33" <?php if(in_array(33,$valarray)){ ?>selected="selected"<?php } ?>>33</option>**
<option value="44">44</option>
**<option value="55" <?php if(in_array(55,$valarray)){ ?>selected="selected"<?php } ?>>55</option>**
</select>
http://www.w3schools.com/tags/att_select_multiple.asp
First of all, change $val into array. Then is select options use in_array() ( http://www.php.net/in_array ) to validate if you need to print selected="selected" in give option.
I guess thats the easiest option
Here is a solution
<?php
$selected_value = "22,33,55";
$selected_value = explode(',', $selected_value);
$all_values = array(11,22,33,44,55); ?>
<select name="choice[]" multiple="multiple"> <?php
foreach($all_values as $option_value ) {
$selected = '';
if(in_array($option_value, $selected_value)){
$selected = "selected";
}?>
<option <?php echo $selected; ?> ><?php echo $option_value; ?></option><?php
} ?>
</selected

A better solution to handle PHP and HTML <option> logic

Wondering if you can show me a better way to handle this logic? I wrote this and am very ashamed of it. Can you show me a better optimized version of this logic?
P.S $result["item"]; returns an integer.
$type = $result["item"];
switch ($type){
case "1":
$type_output = '
<option value="1" selected>Cash</option>
<option value="2">Cheque</option>
<option value="3">Debit Card</option>
<option value="4">Credit Card</option>';
break;
case "2":
$type_output = '
<option value="1">Cash</option>
<option value="2" selected>Cheque</option>
<option value="3">Debit Card</option>
<option value="4">Credit Card</option>';
break;
case "3":
$type_output = '
<option value="1">Cash</option>
<option value="2">Cheque</option>
<option value="3" selected>Debit Card</option>
<option value="4">Credit Card</option>';
break;
case "4":
$type_output = '
<option value="1">Cash</option>
<option value="2">Cheque</option>
<option value="3">Debit Card</option>
<option value="4" selected>Credit Card</option>';
break;
}
html
<td>
<select style="width:200px;" name="payment_type">
<option value=""> </option>
'.$type_output.'
</select>
</td>
Thank you
I would use this approach
$type = $result["item"];
$type_output = "";
$options =array(
"1"=>"cash",
"2"=>"Cheque",
"3"=>"Debit Card",
"4"=>"Credit Card",
);
foreach($options as $value=>$text) {
$type_output .= "<option value=\"$value\"".($type==$value? " selected" : "").">$text</option>\n";
}
you could do it this way and only once
<option value="1" <?php if ($type == 1) echo "selected"; ?>>Cash</option>
<option value="2" <?php if ($type == 2) echo "selected"; ?>>Cheque</option>
<option value="3" <?php if ($type == 3) echo "selected"; ?>>Debit Card</option>
<option value="4" <?php if ($type == 4) echo "selected"; ?>>Credit Card</option>
You're repeating a lot of stuff here. You can do something like
<option value="..." <?php if($type == 1) { print "selected"; } ?> >Something</option>
This would work, however you're probably better off using a template engine and letting it handle this sort of stuff for you.
http://www.smarty.net/docsv2/en/language.function.html.options.tpl
Try this
type_output = '
<option value="1"'.($type == 1 ? " selected" : "").'>Cash</option>
<option value="2"'.($type == 2 ? " selected" : "").'>Cheque</option>
<option value="3"'.($type == 3 ? " selected" : "").'>Debit Card</option>
<option value="4"'.($type == 4 ? " selected" : "").'>Credit Card</option>';
Try this in your document:
<option value="1" <?php if ($type == 1) echo 'selected="selected"' ?>>Cash</option>
<option value="2" <?php if ($type == 2) echo 'selected="selected"' ?>>Cheque</option>
<option value="3" <?php if ($type == 3) echo 'selected="selected"' ?>>Debit Card</option>
<option value="4" <?php if ($type == 4) echo 'selected="selected"' ?>>Credit Card</option>'
Bear in mind that selected on its own is invalid, at least in XHTML. You might get away with it in HTML5, but personally I'd do it properly, as above. Either way, make sure you check your HTML output against the W3C validator.
Also, I tend not to wrap large blocks of HTML in PHP strings, as you have done; it is better to use HTML mode and break into PHP where dynamic output is required. This allows your IDE to understand the structure of your document, and allows syntax colouration and auto-complete to work.
Ashamed)))
sel = document.getElementById("select_id");
if($type>=0&&$type<sel.options.length)
sel.options[$type].selected=true;
do it onLoad or better onDomReady... or just after you options code. Don't forget to assign an id:
<select id="select_id">...
if you're controlling an input, then it would be JUST ONE LINE of JS:
document.getElementById("select_id").options[$type].selected=true;
You could use a function like this:
function selected($selected, $current) {
if($selected == $current)
return "selected";
}
And then:
$options = array(
1 => 'Cash',
2 => 'Cheque',
3 => 'Debit Card',
4 => 'Credit Card'
);
foreach($options as $value => $option)
echo '<option value="'.$value.'" '.selected($value, $type).'>'.$option.'</option>';
Note that the selected function is applicable in other similar cases too.
Here's how I'd do it.
$options = array(
"1"=>"Cash",
"2"=>"Cheque",
"3"=>"Debit Card",
"4"=>"Credit Card"
);
$type = $result['item'];
$type_output = "";
foreach($options as $value=>$text) {
if($value==$type){
$selected = " selected";
}
else {
$selected = "";
}
$type_output .= '<option value="'.$value.'"'.$selected.'>'.$text.'</option>';
}
Just noticed Chumkiu had a similar answer, but I'll post mine anyway in case this is clearer to some folk than the ternary if statement

how to put value in select option

I have select option in my page or drop down list,my problem is how can i set value
in my select option and this value is from the database,
here is my code.
<select name="status" value="<?php echo $status; ?>" >
<option value=""></option>
<option value="public">public</option>
<option value="private">private</option>
</select>
on top of my html tag
if(isset($_GET['status']))
{
$status = $_GET['status'];
$sstatus="select .......";
foreach($db->query($sstatus) as $rows)
{
$status= $rows['status'];
......
......
......
}
}
I tried modify my code and it's seems working but my problem is that it has 2 same
value in the drop down list.
<select name="status" >
<option selected="selected"><?php echo $status; ?></option>
<option value="public">public</option>
<option value="private">private</option>
</select>
it will show like this in my drop down list,my question for this is this is the right way
in displaying the values that comes from the database.
public
public
private
<select name="status" >
<option value=""></option>
<option value="public"<?php if (isset($status) && $status === 'public') echo 'selected'; ?>>public</option>
<option value="private"<?php if (isset($status) && $status === 'private') echo 'selected'; ?>>private</option>
</select>
<?php $options = array('', 'public', 'private') ?>
<select name="status">
<?php foreach ($options as $option): ?>
<option value="<?php echo $option ?>" <?php echo isset($status) && $status == $option ? 'selected="selected"' : '' ?>><?php echo $option ?></option>
<?php endforeach ?>
</select>

JQuery/PHP: Replace a select box with another select box on a different page

On my main page, I have a simple dropdown box:
<select name="miles" id="miles">
<option value="5">5</option>
<option value="10">10</option>
<option value="15">15</option>
<option value="25">25</option>
<option value="50">50</option>
<option value="75">75</option>
<option value="100">100</option>
</select>
<button type="button" name="button" id="button">Search</button>
When this button is clicked, it performs a JQuery $.load:
$("#miles").load("main_data.php #miles_data");
And here the page button is calling, main_data.php:
<?php
... code to calculate $b
?>
<span id="miles_data">
<option value="5" <?php if ($b == 5) { echo "selected"; } ?>>5</option>
<option value="10" <?php if ($b == 10) { echo "selected"; } ?>>10</option>
<option value="15" <?php if ($b == 15) { echo "selected"; } ?>>15</option>
<option value="25" <?php if ($b == 25) { echo "selected"; } ?>>25</option>
<option value="50" <?php if ($b == 50) { echo "selected"; } ?>>50</option>
<option value="75" <?php if ($b == 75) { echo "selected"; } ?>>75</option>
<option value="100" <?php if ($b == 100) { echo "selected"; } ?>>100</option>
</span>
My goals seem simple: Execute a $.load to another page, calculate an integer and set it to a variable, select the matching dropdown item and return it to the main page.
With my code above, the dropdown box on the main page becomes blank. Does anyone notice a solution?
One possible issue is that the format for a selected 'option' is:
<select>
<option>Volvo</option>
<option selected="selected">Saab</option>
<option>Mercedes</option>
<option>Audi</option>
</select>
Blatantly ripped from here
So you want to have
<option value="5" <?php if ($b == 5) { echo 'selected="selected"'; } ?>>5</option>

Categories