I have a select (dropdown) box. On each button click, I'd like it to load previously saved position. My code is:
<select name="myVariables" style="width:150px">
<?php
foreach ( $variables as $var ) {
echo "<option value=\"" . $var . "\"". $var . " </option>";}
?>
</select>
I have a variable $previouslySelected, and every time the button is clicked, this variable can change. I'd like to also change the currently selected option in the select box to the same value. I've tried with:
echo "<option value=\"" . $var . "\" <?=$previouslySelected==$var ? ' selected=\"selected\"' : '';?\>>". $var . " </option>";}
but this doesn't seem to work.
Also, I've tried this but it only works the first time.
How do you submit the form. With GET or POST?
With GET, than you must take the submitted value in this way:
$previouslySelected = isset($_GET['myVariables']) ? $_GET['myVariables'] : '';
Otherwise with POST:
$previouslySelected = isset($_POST['myVariables']) ? $_POST['myVariables'] : '';
In PHP 7 you can also do:
$previouslySelected = $_POST['myVariables'] ?? '';
EDIT: Write your echo more readable.
$selected = ($previouslySelected === $var) ? ' selected="selected"' : '';
echo '<option value="' . $var . '" ' . $selected . '>' . $var . '</option>';
Related
I have a wordpress site with a search form that searches for posts based on the form field selections, for custom fields etc. It works fine, however on the search results page I have an exact copy of the form except that I am trying to preset the form selections based on the search query/url string.
I am using a regular select dropdown and I have set it to "multiple" so that it can use bootstraps multiselect with the checkboxes. I've asked a similar question HERE but that was for checkboxes and even though the bootstrap multiselect uses checkboxes, I still have to work with the select dropdown first.
So after trying several things, I've come close but have ran into several problems. In the code below I made notes to further explain exactly what I mean.
<select name="property_type[]" id="pt-multi" class="form-control multi-select2" multiple="multiple">
<?php
$terms = get_terms( "property-type", array( 'hide_empty' => 0 ) );
$count = count($terms);
if ( $count > 0 ){
echo "<option value='Any'>All</option>";
foreach ( $terms as $term ) {
if (isset($_GET['property_type'])) {
foreach ($_GET['property_type'] as $proptypes) {
// FIRST EXAMPLE
$selected .= ($proptypes === $term->slug) ? "selected" : ""; // shows first correct selected value but also selects everything after it up until the second correct value, which it doesn't select.
//$selected = ($proptypes === $term->slug) ? "selected" : ""; // shows only last correct selected value
//if ($proptypes === $term->slug) { $selected = 'selected'; } // shows first correct selected value then selects every value after, even if it wasn't selected
// SECOND EXAMPLE
//$selected .= ($proptypes === $term->slug) ? "selected" : ""; // shows first correct selected value then selects every value after, even if it wasn't selected
//$selected = ($proptypes === $term->slug) ? "selected" : ""; // shows only last correct selected value
//if ($proptypes === $term->slug) { $selected = 'selected'; } // shows first correct selected value then selects every value after, even if it wasn't selected
}
}
echo "<option value='" . $term->slug . "' " . $selected . ">" . $term->name . "</option>"; // FIRST EXAMPLE
//echo "<option value='" . $term->slug . "' " . ($selected?' selected':'') . ">" . $term->name . "</option>"; // SECOND EXMAPLE
}
}
?>
</select>
Create and array and use in_array() to check.
<select name="property_type[]" id="pt-multi" class="form-control multi-select2" multiple="multiple">
<?php
$terms = get_terms("property-type", array('hide_empty' => 0));
$count = count($terms);
// Setup an array of $proptypes
$proptypes = array();
if (isset($_GET['property_type'])) {
foreach ($_GET['property_type'] as $proptype) {
$proptypes[] = $proptype;
}
}
if ($count > 0) {
echo "<option value='Any'>All</option>";
foreach ($terms as $term) {
$selected = (in_array($term->slug, $proptypes)) ? 'selected' : '';
echo "<option value='" . $term->slug . "' " . $selected . ">" . $term->name . "</option>";
}
}
?>
</select>
I know this should be simple but I just can't seem to get my head around it.
I have a list of continents in a sql database that I get back using PHP DBO and display in a drop down list. What I then want to do is get the users preferred continent from the sql database and select that one in the list. E.g if the list contains World, Africa, Europe, N America and S America but the users favorite is 'Europe' I want that one selected. $getContinent is the users preference.
while ($row = $continent_results->fetch(PDO::FETCH_ASSOC)) {
if ($getContinent != ''){
echo '<option value="' . $getContinent . '" selected="selected" >' . $row['CONTINENT_NAME'] . '</option>';
}else{
echo '<option value=' . $row['CONTINENT_ID'] . '>' . $row['CONTINENT_NAME'] . '</option>';
}
}
I would be most grateful if someone could set me straight as I have found some examples on the internet but have been unable to get them to work :)
Your code should be like this
while ($row = $continent_results->fetch(PDO::FETCH_ASSOC)) {
//just check if the option id is equal to the chosen value
if ($getContinent != '' && $getContinent==$row['CONTINENT_ID'] ){
echo '<option value="' . $getContinent . '" selected="selected" >' . $row['CONTINENT_NAME'] . '</option>';
}else{
echo '<option value=' . $row['CONTINENT_ID'] . '>' . $row['CONTINENT_NAME'] . '</option>';
}
}
Its simple, as you guessed :D
You would use something like this:
while ($row = $continent_results->fetch(PDO::FETCH_ASSOC)) {
echo '<option value="' . $row['CONTINENT_ID'] . '">' . $row['CONTINENT_NAME'] . '</option>';
}
I hope that helps!
--al
You can use ternary operator
while ($row = $continent_results->fetch(PDO::FETCH_ASSOC)) {
echo '<option value="' . $row['CONTINENT_ID'] .
($getContinent == $row['CONTINENT_NAME']) ? '" selected="selected"' : '"' . '>' .
$row['CONTINENT_NAME'] . '</option>';
}
I have this drop-down and user can select multiple options ,how can i keep selected value on form after submit button, if error comes on form
<select onclick="document.getElementById('cand_qual4').style.display='none'; " name="oca[]" id="oca" multiple="multiple">
<?php
$odrop = array('B COM','M COM','BBA','MBA','LLB','LLM','CPA','CIMA','MS FINANCE','DISA','CISA','OTHER');
foreach ($odrop as $odrop1)
{
echo '<option value="' . $odrop1 . '"' . (isset($_POST['oca']) && in_array($odrop1,$_POST['oca']) ? ' selected' : '') . '>' . $odrop1 . '</option>';
}
?>
</select>
instead of
$_POST['oca'] == $odrop1
condition as $_POST['oca'] would be an array, try
in_array($odrop1,$_POST['oca'])
TRY THIS-
echo '<option value="' . $odrop1 . '"' . (is_array($_POST['oca']) && in_array($odrop1,$_POST['oca'] ) ? ' selected' : '') . '>' . $odrop1 . '</option>';
In PHP Project, I'm creating page a which retrieve the data from database on page load then allow the user to change data & Update. I have to use input text and option controls to display data. Editing form data may involve in few POST requests. To load data from database and retain data between POSTs I use this approach.
Load Data from Database
$oClass = new DataClass();
$oClass ->GetRecordById($_REQUEST['id']);
$dataName = $oClass ->Name;
$dataYear = $oClass ->Year;
INPUT TEXTs
<input type="text" name="txtName" value="<?php echo isset($_POST['txtName']) ? $_POST['txtName'] : $dataName ?>" >
OPTIONs
$arrYears = GetYears();
foreach ($arrYears as $year) {
if (isset($_POST['ddlYear'])) {
if ($_POST['ddlYear'] == $year) {
echo '<option value="' . $year . '" selected="selected">' . $year . '</option>';
} else {
echo '<option value="' . $year . '">' . $year . '</option>';
}
} else {
if ($dataYear == $year) {
echo '<option value="' . $year . '" selected="selected">' . $year . '</option>';
} else {
echo '<option value="' . $year . '">' . $year . '</option>';
}
}
}
Is there a better approach to retain data between posts than using like
if (isset($_POST['NAME']))
{$_POST['NAME']}
else
{$name}
Is there a reason why you need to retain the info? If a user submits the form it will update the info and therefore will need to be fetched again for the next person to come in and update or read.
Above though you assign $year = $oClass ->Year; but it's not referenced anywhere. the $year in the foreach loop is a local scope variable only for that foreach loop, after that loop finishes executing it disappears.
you can do stuff like this.
if (isset($_POST['txtName']))
{
$name = $_POST['txtName'];
}
else
{
$name = '';
}
<input type="text" name="txtName" value="<?php echo $name; ?>" />
Since the only difference between the options in the foreach loops are whether or not the selected attribute is applied you can shorten both of them to the following.
if (isset($_POST['ddlYear'])) {
echo '<option value="' . $year . ($_POST['ddlYear'] == $year) ? '" selected="selected"' : '' . '>' . $year . '</option>';
}
else {
echo '<option value="' . $year . ($movieyear == $year) ? '" selected="selected"' : '' . '>' . $year . '</option>';
}
Also to get a quicker answer please provide the simplest working use case, for example above example has $_POST variables that aren't defined anywhere and others like $movieyear also not defined.
I have a dropdown menu populated from a table in a MySQL database. It functions, but I would like to add an if/else statement to the code to change the default value of the dropdown according to the conditions.
Here is the code for the dropdown (much thanks to AlienWebguy for his assistance in getting this far):
<?php
$sql="SELECT techID, tech_userlogin FROM technicians";
$result=mysql_query($sql);
while ($row=mysql_fetch_array($result))
{
$techID = $row['techID'];
$tech_userlogin=$row['tech_userlogin'];
// Here - check if the $_GET value in the query matches the tech_userlogin
($selected = ($tech_userlogin == $_GET['wtech_userlogin']) ? 'selected="selected"' : '');
echo '<option value="' . $tech_userlogin . '" ' . $selected . '>' . $tech_userlogin . '</option>' . "\n";
}
?>
I've tried a couple of things to accomplish what I'm after, but I'm severely hampered by my lack of experience and/or expertise in PHP/MySQL.
This is the first time I've tried these things and it has been hit and miss so far. I've recieved help here at Stack Overflow and I'm grateful such a resource exists.
This is my latest effort and it fails to achieve what I'm after. I want the default value of the dropdown to be "--Select Technician--" if the condition is not met in the if statement.
<?php
$sql="SELECT techID, tech_userlogin FROM technicians";
$result=mysql_query($sql);
$options="";
while ($row=mysql_fetch_array($result))
{
$techID = $row['techID'];
$tech=$row['tech_userlogin'];
$options.="<option value=\"$tech\">$tech</option>";
// Here - check if the $_GET value in the query matches the tech_userlogin
if
($selected = ($tech == $_GET['wtech_userlogin']) ? 'selected="selected"' : '')
{echo '<option value="' . $tech . '" ' . $selected . '>' . $tech . '</option>' . "\n";}
else
{echo '<option value="' . $options . '" . 'selected="selected"'>'--Select Tech--'<. $options .>' . "\n";}
}
?>
Can someone please help me or point me in the right direction? Many thanks.
Cheers
Try this
<select name="whatever">
<option value="">-- Select Technician --</option>
<?php while ($row = mysql_fetch_array($result)) :
$techId = $row['techID']; // why isn't this used?
$tech = htmlspecialchars($row['tech_userlogin']);
$selected = $row['tech_userlogin'] == $_GET['wtech_userlogin'] ? '" selected="selected' : '';
?>
<option value="<?php echo $tech, $selected ?>"><?php echo $tech ?></option>
<?php endwhile ?>
</select>
If the whole if/then is just there to create a default, you're making it way too complicated.
$options = '<option value="">--Select Tech--</option>';
while ($row=mysql_fetch_array($result))
{
$techID = $row['techID'];
$tech = $row['tech_userlogin'];
$selected = ($tech == $_GET['wtech_userlogin']) ? 'selected="selected"' : '';
$options .= '<option value="' . $techID . '" ' . $selected . '>' . $tech . '</option>' . "\n";
}
Now $options has all of your options in it, including a default option (--Select Tech--, with empty value) that shows up first, and will therefore start out selected if nothing else has the selected attribute.
Note that you also had $tech in the value of your option, but I assumed you meant to say $techID.
You wrote this, which isn't doing what you want:
($selected = ($tech == $_GET['wtech_userlogin']) ? 'selected="selected"' : '')
Change to this:
($selected = ($tech == $_GET['wtech_userlogin']) ? 'selected="selected"' : false)
Notice the 'false'. You need that because empty quotes is not false, it is considered 'true' by PHP.
I could be wrong, but I believe the problem is with your if statement. You have:
($selected = ($tech == $_GET['wtech_userlogin']) ? 'selected="selected"' : '')
The problem is that you are assigning the result of the ternary statement to the variable $selected, which will always return a true for a successful assignment.