how to retain selected values in Select field after form submission? - php

i have a main page that i used in uploading tickets to db, i have Select field that i want to retain the value that the user selected prior to submitting the form but its not happening...
here is my code for select field:
<select name="XiD" id="XiD">
<option value="Blank" selected="selected">Please Select...</option>
<option value="AAA">AAA</option>
<option value="BBB">BBB</option>
<option value="CCC">CCC</option>
<option value="DDD">DDD</option>
<option value="EEE">EEE</option>
<option value="FFF">FFF</option>
</select>
just to add, this Xid is being posted prior to submitting
$XiD = $_POST['XiD'];
and i try to use this script:
UPDATE - changed from $_GET to $_POST but still not working...
<script type="text/javascript">
document.getElementById('XiD').value = "<?php echo $_POST['XiD'];?>";
</script>
my jquery version im using: jquery-ui-1.10.2 and jquery-1.9.1

Use jQuery like this.
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('select#XiD').val('<?php echo $_POST['XiD'];?>');
});
</script>

You are using PHP to generate HTML. There's absolutely no need to use a third language to dictate how that HTML should be!
<select name="XiD" id="XiD">
<option value="Blank"<?=$XiD=='Blank' ? ' selected="selected"' : ''?>>Please Select...</option>
<option value="AAA"<?=$XiD=='AAA' ? ' selected="selected"' : ''?>>AAA</option>
...
</select>
Or, even better, simplify your code with an array and avoid writing duplicate code that's hard to maintain:
<?php
$options = array(
'Blank' => 'Please Select...',
'AAA' => 'AAA',
'BBB' => 'BBB',
'CCC' => 'CCC',
'DDD' => 'DDD',
'EEE' => 'EEE',
'FFF' => 'FFF',
);
<select name="XiD" id="XiD">
<?php foreach(options as $k => $v){ ?>
<option value="Blank"<?php echo $XiD==$k ? ' selected="selected"' : ''?>>Please Select...</option>
<? } ?>
</select>

According to your problem, it seems like you are using POST method (because you are getting value to $XiD = $_POST['XiD'];) and using GET to retrieve value.
So, use document.getElementById('XiD').value = "<?php echo $_POST['XiD'];?>";
instead of
document.getElementById('XiD').value = "<?php echo $_GET['XiD'];?>";

I would create a function to check if the current GET value is the same as the option in the list and in that case, return the needed attribute to make it selected by default, which is selected="selected".
This should work:
<?php
function isSelected($value){
if($value == $_GET['XiD']){
return 'selected="selected"';
}else{
return '';
}
}
?>
<select name="XiD" id="XiD">
<option value="Blank" <? echo isSelected('Blank');?>>Please Select...</option>
<option value="AAA" <? echo isSelected('AAA');?>>AAA</option>
<option value="BBB" <? echo isSelected('BBB');?>>BBB</option>
<option value="CCC" <? echo isSelected('CCC');?>>CCC</option>
<option value="DDD" <? echo isSelected('DDD');?>>DDD</option>
<option value="EEE" <? echo isSelected('EEE');?>>EEE</option>
<option value="FFF" <? echo isSelected('FFF');?>>FFF</option>
</select>

After trying al this "solves" nothing work. Did some research on w3school before and remember there was explanation of keeping values about radio. But it also works for Select option. See here an example. Just try it out and play with it.
<?php
$example = $_POST["example"];
?>
<form method="post">
<select name="example">
<option <?php if (isset($example) && $example=="a") echo "selected";?>>a</option>
<option <?php if (isset($example) && $example=="b") echo "selected";?>>b</option>
<option <?php if (isset($example) && $example=="c") echo "selected";?>>c</option>
</select>
<input type="submit" name="submit" value="submit" />
</form>

Related

PHP: How to display select options if no value from database

I am trying to display my dropdown with a value from the database, but if the value is null I want it to show my options.
Currently it keeps showing me the blank select option.
<select class="form-control col-sm-5" id="freqlevels" name="freqlevels" value="<?php if ($customerinfo['freqlevel']) { echo h($customerinfo['freqlevel']);} else { echo "" ; } ?>"">
<option value=""></option>
<option value="Twice Weekly">Twice Weekly</option>
<option value="Weekly">Weekly</option>
<option value="Fortnightly">Fortnightly</option>
<option value="Monthly">Monthly</option>
</select>
Please can you suggest what I should do?
put your condition outside the value
<?php if ($customerinfo['freqlevel']) { echo value="$customerinfo['freqlevel']";}
hope this will resolve your problem
You need to make use of conditional statements.
<select name="something" id="my-select">
<option value="0">Everyone can see me</option>
<?php if (empty($array['some_key'])) : ?>
<option value="1">I'm only if some_key is empty</option>
..etc..
<?php endif; ?>
</select>
Then you can check values against the option value:
<option value="<?php echo $key; ?>"
<?php echo ($key === $_POST['some_key'] ? 'selected' : ''); ?>>
Hello, world
</option>

Using $_POST to get select option value from HTML

I use select as below:
<select name="taskOption">
<option>First</option>
<option>Second</option>
<option>Third</option>
</select>
How do I get the value from the select option and store it into a variable for future use, in PHP?
Use this way:
$selectOption = $_POST['taskOption'];
But it is always better to give values to your <option> tags.
<select name="taskOption">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
</select>
You can access values in the $_POST array by their key. $_POST is an associative array, so to access taskOption you would use $_POST['taskOption'];.
Make sure to check if it exists in the $_POST array before proceeding though.
<form method="post" action="process.php">
<select name="taskOption">
<option value="first">First</option>
<option value="second">Second</option>
<option value="third">Third</option>
</select>
<input type="submit" value="Submit the form"/>
</form>
process.php
<?php
$option = isset($_POST['taskOption']) ? $_POST['taskOption'] : false;
if ($option) {
echo htmlentities($_POST['taskOption'], ENT_QUOTES, "UTF-8");
} else {
echo "task option is required";
exit;
}
You can do it like this, too:
<?php
if(isset($_POST['select1'])){
$select1 = $_POST['select1'];
switch ($select1) {
case 'value1':
echo 'this is value1<br/>';
break;
case 'value2':
echo 'value2<br/>';
break;
default:
# code...
break;
}
}
?>
<form action="" method="post">
<select name="select1">
<option value="value1">Value 1</option>
<option value="value2">Value 2</option>
</select>
<input type="submit" name="submit" value="Go"/>
</form>
for php8+ versions, you can use match expression:
$select = $_POST['select1'] ?? '';
$result = match ($select) {
'value1' => 'this is value1',
'value2' => 'this is value2',
default => 'unknown value',
};
echo $result;
<select name="taskOption">
<option value="first">First</option>
<option value="second">Second</option>
<option value="third">Third</option>
</select>
$var = $_POST['taskOption'];
Depends on if the form that the select is contained in has the method set to "get" or "post".
If <form method="get"> then the value of the select will be located in the super global array $_GET['taskOption'].
If <form method="post"> then the value of the select will be located in the super global array $_POST['taskOption'].
To store it into a variable you would:
$option = $_POST['taskOption']
A good place for more information would be the PHP manual: http://php.net/manual/en/tutorial.forms.php
Like this:
<?php
$option = $_POST['taskOption'];
?>
The index of the $_POST array is always based on the value of the name attribute of any HTML input.
<select name="taskOption">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
</select>
try this
<?php
if(isset($_POST['button_name'])){
$var = $_POST['taskOption']
if($var == "1"){
echo"your data here";
}
}?>
-- html file --
<select name='city[]'>
<option name='Kabul' value="Kabul" > Kabul </option>
<option name='Herat' value='Herat' selected="selected"> Herat </option>
<option name='Mazar' value='Mazar'>Mazar </option>
</select>
-- php file --
$city = (isset($_POST['city']) ? $_POST['city']: null);
print("city is: ".$city[0]);

<select> dropdown default value

I have this code:
if(isset($_POST['search']))
{
$res1=mysql_query("SELECT * FROM aircraft where acode = '$_POST[ac]'") or die(mysql_error());
while($row=mysql_fetch_array($res1))
{
$airc=$row['acode'];
$amode=$row['amodel'];
$stat=$row['status'];
$rem=$row['remarks'];
echo "<center><table><form name=\"frmMain\" method=\"post\">
<tr><td><font face=consolas><b>Aircraft Code:</b></font></td><td><input type=text name=arc value='$airc' readonly=readonly></td></tr>
<tr><td><font face=consolas><b>Aircraft Model:*</b></font></td><td><input type=text name=am value='$amode'></td></tr>
<tr><td><font face=consolas><b>Status:*</b></font></td><td><input type=text name=st value='$stat'></td></tr>
<tr><td><font face=consolas><b>Remarks:*</b></font></td><td><input type=text name=rm value='$rem'></td></tr></table>";
}
}
On submit 'search' button, this code displays the data from aircraft table. The user is allowed to update the data with the (*) sign.
Since the Status are the following by default (Available, Not Available), I changed this
<tr><td><font face=consolas><b>Status:*</b></font></td><td><input type=text name=st value='$stat'></td></tr>
to this,
<tr><td><font face=consolas><b>Status:*</b></font></td><td><select name=st>
<option value=Available>Available</option>
<option value='Not Available'>Not Available</option>
</select></td></tr>
But I want the dropdown to have it's default value depending on
$stat=$row['status']; since this is an update form.
If the data being retrieved has it's status 'Available', then the dropdown should have it's default value as 'Available'.
How can I achieve that? I tried <select name=status value='$stat'> but it doesn't work. Any help will be appreciated. Thanks!
Just put selected="selected" on the option depending on your $row['status'],
<option selected="selected" value="available">Available</option>
write Available and Unavailable into an array
$theArray = array("Available","Not Available");
loop the array:
<tr><td><font face=consolas><b>Status:*</b></font></td><td><select name=st>
<?php
foreach ($theArray as $key => $value) {
if ($value == $stat) {
echo('<option selected="selected" value='.$value.'>'.$value.'</option>');
} else {
echo('<option value='.$value.'>'.$value.'</option>');
}
}
?>
</select></td></tr>
and in each loop we check if the value in the array, is the same as it is in the variable, if so, we put the selected there
understand the logic?
<select name=status>
<option value="available" <?php if($row['status']=="available") echo "selected=\"selected\""; ?>>Available</option>
<option value="unavailable" <?php if($row['status']=="unavailable") echo "selected=\"selected\""; ?>>Unvailable</option>
</select>
Basically echo selected="selected" for the option depending on value of the concerned field.
<?php
$status = "navail";
?>
<select name="sel">
<option value="avail" <?php if($status == "avail") echo "SELECTED";?> > Avail </option>
<option value="navail" <?php if($status == "navail") echo "SELECTED";?> > Navail </option>
</select>
You can define your variable value with additional option tag and mark that as selected like:
<select name="role" id="role">
<!-- This is default define value using php variable $r -->
<option selected="selected" value="<?php echo $r; ?>" disabled="disabled"><?php echo $r; ?></option>
<!-- Other options values -->
<option value="2">Option-2</option>
<option value="2">Option-2</option>
</select>
You can set the selected dropdown option from database as below:
<select name="status">
<option <?php echo ($row['status'] == 'Available') ? 'selected' : '' ?> value='Available'>Available</option>
<option <?php echo ($row['status'] == 'Not Available') ? 'selected' : '' ?> value='Not Available'>Not Available</option>
</select>
Declare the options in an array like
$arr = array("available" => "available","unavailable" => "unavailable");
and input the drop down like this
echo form_dropdown("st", $arr, set_value("st", (isset($row['status'];) ? $row['status']; : ""))
This is the method commonly used in frameworks like codeigniter.. i think it works in core php too..
its my first time here though and i tried using basic principles in php, dont know if this helps you but if you're trying to grab the defaulted value which you inputted on your database then edit it again i suggest you try this one
<select name="st">
<?php if($row['status']=="Available"){?><option value="Available">Available</option><?php }?>
<?php if($row['status']=="Unavailable"){?><option value="Unavailable">Unavailable</option><?php }?>
</select>
Assuming that the column name in your database is 'status', give it a try works for me

make a value selected in drop down when editing

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

select option clears when page loads in php

the scenario is this: see select below
<form name="limit">
<select name="limiter" onChange="limit(this.value)">
<option selected="selected"> </option>
<option value="5">5</option>
<option value="10">10</option>
<option value="15">15</option>
</select>
</form>
I want whenever any option is selected for 3 things to happen:
1.) js limit() function is called which all it does its takes current url, adds new query parameter 'limit' with the user selected value eg:
http://localhost/blahblah/apps/category.php?pg=1&catId=3021&limit=5
(this will cause the category.php page to be hit and # of product displayed limited to the value selected by user)
2.)Once the url is hit, it reloads but i DONT want the value selected to reset back to the default (which it currently does). I want it to reflect the users selection after page reload.
3.) Also, when i move to the next page (pagination), i would like the state to be carried ova to the next page (ie. remembering the user selection).
Just assign the selected value using PHP:
<form name="limit">
<select name="limiter" onChange="limit()">
<option <?php if(!isset($_POST['limiter'])) echo ' selected="selected"'; ?>> </option>
<option <?php if(isset($_POST['limiter']) && $_POST['limiter'] == 5) echo ' selected="selected"'; ?> value="5">5</option>
<option <?php if(isset($_POST['limiter']) && $_POST['limiter'] == 10) echo ' selected="selected"'; ?> value="10">10</option>
<option <?php if(isset($_POST['limiter']) && $_POST['limiter'] == 15) echo ' selected="selected"'; ?> value="15">15</option>
</select>
</form>
As the code gets hard to read, you could do a loop instead with PHP:
<form name="limit">
<select name="limiter" onChange="limit()">
<option <?php if(!isset($_POST['limiter'])) echo ' selected="selected"'; ?>> </option>
<?php foreach(array(5, 10, 15) as $p): ?>
<option <?php if(isset($_POST['limiter']) && $_POST['limiter'] == $p) echo ' selected="selected"'; ?> value="<?php echo $p; ?>">
<?php echo $p; ?>
</option>
<?php endforeach; ?>
</select>
</form>
<script type="text/javascript">
function limit(value)
{
url = "localhost/yourapp?limiter="+value;
}
</script>
<form name="limit">
<select name="limiter" onChange="limit(this.value)">
<option> </option>
<option value="5" <?php if($_REQUEST['limiter'] == 5) {echo "selected";}?>>5</option>
<option value="10" <?php if($_REQUEST['limiter'] == 10) {echo "selected";}?>>10</option>
<option value="15" <?php if($_REQUEST['limiter'] == 15) {echo "selected";}?>>15</option>
</select>
</form>
I am using $_REQUEST here because I don't know your form's method. Use accordingly.
Tatu Ulmanen's answer handles the part of displaying select. To do the pagination part, simply pass the limit as a parameter in the query string.
For example, if you're currently using page links that look like this:
1
Change them to include your limit parameter so it gets passed over:
1
Just make sure to change your pagination code to account for the fact that each page is only "limit" items long. To help you do that, I need to know how you were doing your pagination.
can you check whether it works?
<script type="text/javascript">
function limit(myvalue)
{
location.href="http://yoursite?limit="+myvalue;
}
function querySt() {
hu = window.location.search.substring(1);
gy = hu.split("&");
for (i=0;i<gy.length;i++) {
ft = gy[i].split("=");
if (ft[0] == 'limit') {
for (var idx=0;idx<document.getElementById('limiter').options.length;idx++) {
if (document.getElementById('limiter').value==ft[1]) {
document.getElementById('limiter').selectedIndex=idx;
}
}
}
}
}
</script>
</head>
<body onload="querySt()">
<form name="limits">
<select onchange="limit(this.value)" id="limiter">
<option selected="selected"> </option>
<option value="5">5</option>
<option value="10">10</option>
<option value="15">15</option>
</select>
</form>
</body>

Categories