I am adding a feature to edit the ads a user puts. For that I want to make the value selected which is selected by the user when he entered the values . How can I implement this?
<div class="nm">
Category
</div>
<div class="fl">
<select name="category" id = "ad_category" onchange="cangeSubCat(this.value)" >
<option value="">---Select Category---</option>
<option value="real_estate">Real Estate</option>
<option value="hotels_resturants">Hotels and Resturants</option>
<option value="car">Car Rental</option>
</select>
</div>
Add the selected HTML <option> attribute, in XHTML it is selected="selected".
<option value="value" selected>title</option>
^^^^^^^^
Documentation: http://www.w3.org/TR/html4/interact/forms.html#h-17.6.1
I mean how will I know which one should be selected..it will be different for different users . I wnt it to be selected which user selects during adding the ad
That depends on your code. You can do this with an array with all value/title pairs (value => title) and the value which is selected. Then when key (value) equals the selected one, the attribute is added in output. As it's an array it's easy to iterate over it.
$otpions = array(
'a' => 'A',
'b' => 'B',
);
$selected = 'b';
echo '<select>';
foreach ($options as $value => $title)
{
printf('<option value="%s" %s>%s</option>',
$value, $selected == $value ? 'selected' : '', $title);
}
echo '</select>';
okay lets assume you fetch value from db and that select box value is in $select variable then you've to write
<option <?php if($select=="real_estate") { echo "selected='selected'"; } ?> value="real_estate">Real Estate</option>
<option <?php if($select=="hotels_resturants") { echo "selected='selected'"; } ?> value="hotels_resturants">Hotels and Resturants</option>
<option <?php if($select=="car") { echo "selected='selected'"; } ?> value="car">Car Rental</option>
You can use this magic function
function __selectedDb($ctrlValue,$dbValue)
{
if($ctrlValue == $dbValue)
return "selected='selected'";
else
return "";
}
like
<select name="category" id = "ad_category" onchange="cangeSubCat(this.value)" >
<option value="" <?php echo __selectedDb("","$cat")?>>---Select Category---</option>
<option value="real_estate" <?php echo __selectedDb("real_estate","$cat")?>>Real Estate</option>
<option value="hotels_resturants" <?php echo __selectedDb("hotels_resturants","$cat")?>>Hotels and Resturants</option>
<option value="car" <?php echo __selectedDb("car","$cat")?>>Car Rental</option>
</select>
I write in core php please convert php code to smarty
Related
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>
I have a drop down menu that checks whether a user has already selected a value by checking database and if they have, I want to add a 'selected' attribute to that option so that when they edit their profile, that option is preselected by what they chose.
Heres an example of what I am trying to accomplish. It works for text inputs but I don't know how to do it with dropdown lists.
So if user selects 'Dog', it gets place in database and adds 'selected' as attribute
$animal = $mysqli->escape_string($_POST['animal']);
//PHP UPDATE database script -------->
<label>Animal</label></br>
<select name='animal' value='<?php if($animal == value){ /*Add selected attribute to option */ ?>'>
<option value="" disabled selected>Select One</option>
<option value="" disabled>----------------</option>
<option value="Dog">Dog</option>
<option value="Cat">Cat</option>
<option value="Bird">Bird</option>
</select>
Define an array of options
$animals = ['Dog', 'Cat', 'Bird'];
Then generate the list of options for the <select> from that array, checking the selected animal against each one. If it matches, then add the selected attribute.
<label>Animal</label></br>
<select name='animal'>
<!-- select the default if none of the options are selected -->
<option value="" disabled <?php if (!in_array($animal, $animals)) echo 'selected' ?>>
Select One
</option>
<option value="" disabled>----------------</option>
<?php foreach ($animals as $option) {
echo "<option ";
if ($animal == $option) {
echo 'selected';
}
echo ">$option</option>";
?>
</select>
value attributes aren't required for your <option> elements in this case, since you're using the same values for the option text. (If the value attribute is omitted, the option text will be used as the value.)
Try it like this:
$animal = $mysqli->escape_string($_POST['animal']);
//PHP UPDATE database script -------->
echo '<label>Animal</label></br>
<select name="animal">
<option value="" disabled>Select One</option>
<option value="" disabled>----------------</option>
<option value="Dog" ' . ($animal == 'Dog' ? 'selected' : '') . '>Dog</option>
<option value="Cat" ' . ($animal == 'Cat' ? 'selected' : '') . '>Cat</option>
<option value="Bird" ' . ($animal == 'Bird' ? 'selected' : '') . '>Bird</option>
</select>';
I have this HTML/PHP Code that lists options in a select element.
Whats the best way to make the correct option selected based on a record from a MySQL database:
This works fine, but is there any easier way to do it with one line of code rather than doing an if statement per option?
<select name="status" id="status">
<option value="Open"<?php if($ticket["status"]=="Open"){echo('selected="selected"');}?>>Open</option>
<option value="Needs Action"<?php if($ticket["status"]=="Needs Action"){echo('selected="selected"');}?>>Needs Action</option>
<option value="Customer Reply"<?php if($ticket["status"]=="Customer Reply"){echo('selected="selected"');}?>>Customer Reply</option>
<option value="Completed"<?php if($ticket["status"]=="Completed"){echo('selected="selected"');}?>>Completed</option>
</select>
use an array:
echo "<select name='status' id='status'>";
$statuses = array('Open', 'Needs Action', 'Customer Reply', 'Completed');
foreach ($statuses as $status) {
echo "<option value='$status' " . ($ticket['status'] == $status) ? "selected='selected'" : "" . "/>";
}
echo "</select>";
You may want to put those values in the database or if you want to avoit it, just put them into an array and print all the options using a loop and mark as selected the right one.
Yes, the code can be shorter (and much more readable):
if($ticket["status"]=="Open") {
$openSelected = "selected='selected'";
}
if($ticket["status"]=="Needs Action") {
$needsActionSelected = "selected='selected'";
}
if($ticket["status"]=="Customer Reply") {
$customerReplySelected = "selected='selected'";
}
if($ticket["status"]=="Completed") {
$completedSelected = "selected='selected'";
}
<select name="status" id="status">
<option value="Open" <?php print($openSelected) ?>>Open</option>
<option value="Needs Action"<?php print($needsActionSelected) ?>>Needs Action</option>
<option value="Customer Reply"<?php print($customerReplySelected) ?>>Customer Reply</option>
<option value="Completed"<?php print($completedSelected) ?>>Completed</option>
</select>
EDIT// #Barmar has a better answer.
I have a db_field (shortcode) that returns a string when submited query. the value from that return is AB,EF,GH (exactly this!
The second part is that i have a textarea with a list of that shortcodes. So i trying to highlight (selected) the same macthed elements.
for example:
$String_in_Database = AB,EF,GH;
Wish to have that:
<select name="Country[]" id="Country" multiple="multiple" size="5">
<option value="AB" selected>AB</option>
<option value="CD">CD</option>
<option value="EF" selected>EF</option>
<option value="GH" selected>GH</option>
......
</select>
This is how i generate the options:
<?php $MyArray = $settingsUser['set_disallowcountries']; ?>
<?php foreach($disallCountry as $key => $value) { ?>
<option value="<?php echo $value['short'] ?>" <?php if(is_array($value['short'], $MyArray)) { echo 'selected'; }?>><?php echo $value['long'] ?></option>
<?php } ?>
Maybe you want to explode this string into array?
$MyArray = explode(",",$String_in_Database);
Im slightly unsure to the question, so you want to check if the user has the selected country and have it selected in the option dropdown/box?
<?php
$userSelected= explode(",", $string_in_database);
$allCountries = array('AA', 'BB', 'CC');
foreach($allCountries as $country)
if(in_array($country["short"], $myArray){
$selected = 'selected';
} else {
$selected = '';
}
echo '<option value="'.$country["short"].'" '.$selected.'>'.$country["long"].'</option>';
}
With this, if the user string from the database (im guessing that is the users settings) is the same as AA, BB or CC, they will be selected, if it is not, they won't be selected.
To my knowledge I think this should work, I may be wrong as I have not tested it though. Just my thoughts!
I have a form which is displayed when there is some editing is required in data. This form contains the multiple select box field i.e.,
<select name="multiple" multiple>
<option value="1">asd</option>
<option value="2">asaad</option>
<option value="3">aslan</option>
</select>
Now when i come to this form, I get every existing values populated in their respective fields but i do not get this multiple select box populated. In db the its respective values are stored in csv format like, 2,3,4.
Now how Can i use these csv and repopulate the multiple select box respective of the csv.?
<?
$csvString = "1,3";
?>
<select name="multiple" multiple>
<option value="1" <?=strpos($csvString ,'1')!== false?'selected="selected"':''?> >Option 1</option>
<option value="2" <?=strpos($csvString ,'2')!== false?'selected="selected"':''?> >Option 2</option>
<option value="3" <?=strpos($csvString ,'3')!== false?'selected="selected"':''?> >Option 3</option>
</select>
I assume you generate HTML for selectbox iterating over the $options. Then you just have to check in each iteration if the current value is present in you $csv and add the selected parameter to the option.
$selection = explode(',', $csv);
foreach ($options as $value => $name) {
$selected = in_array($value, $selection) ? ' selected="selected"' : '';
echo '<option value="'. $value .'"'. $selected .'>'. $name .'</option>';
}
This may help but there is probably a better way...
$csvString = "1,3";
$options = explode(",", $csvString);
foreach($options as $val) {
${"opt".$val} = "selected=\"selected\"";
}
?>
<select ...>
<option value="1" <?php echo $opt1 ?> >Option 1</option>
<option value="2" <?php echo $opt2 ?> >Option 2</option>
<option value="3" <?php echo $opt3 ?> >Option 3</option>
</select>