I currently have a form built in which after validation, if errors exist, the data stays on screen for the consumer to correct. An example of how this works for say the 'Year of Birth' is:
<select name="DOB3">
<option value="">Year</option>
<?php
for ($i=date('Y'); $i>=1900; $i--)
{
echo "<option value='$i'";
if ($fields["DOB3"] == $i)
echo " selected";
echo ">$i</option>";
}
?>
</select>
If an error is found, the year of birth value returns the year previously entered. I am able to have this work on all field with the exception of my 'State' field. I build the array and function for the drop down with the following code:
<?php
$states_arr = array('AL'=>"Alabama",'AK'=>"Alaska",'AZ'=>"Arizona",'AR'=>"Arkansas",'CA'=>"California",'CO'=>"Colorado",'CT'=>"Connecticut",'DE'=>"Delaware",'DC'=>"District Of Columbia",'FL'=>"Florida",'GA'=>"Georgia",'HI'=>"Hawaii",'ID'=>"Idaho",'IL'=>"Illinois", 'IN'=>"Indiana", 'IA'=>"Iowa", 'KS'=>"Kansas",'KY'=>"Kentucky",'LA'=>"Louisiana",'ME'=>"Maine",'MD'=>"Maryland", 'MA'=>"Massachusetts",'MI'=>"Michigan",'MN'=>"Minnesota",'MS'=>"Mississippi",'MO'=>"Missouri",'MT'=>"Montana",'NE'=>"Nebraska",'NV'=>"Nevada",'NH'=>"New Hampshire",'NJ'=>"New Jersey",'NM'=>"New Mexico",'NY'=>"New York",'NC'=>"North Carolina",'ND'=>"North Dakota",'OH'=>"Ohio",'OK'=>"Oklahoma", 'OR'=>"Oregon",'PA'=>"Pennsylvania",'RI'=>"Rhode Island",'SC'=>"South Carolina",'SD'=>"South Dakota",'TN'=>"Tennessee",'TX'=>"Texas",'UT'=>"Utah",'VT'=>"Vermont",'VA'=>"Virginia",'WA'=>"Washington",'WV'=>"West Virginia",'WI'=>"Wisconsin",'WY'=>"Wyoming");
function showOptionsDrop($array, $active, $echo=true){
$string = '';
foreach($array as $k => $v){
$s = ($active == $k)? ' selected="selected"' : '';
$string .= '<option value="'.$k.'"'.$s.'>'.$v.'</option>'."\n";
}
if($echo) { echo $string;}
else { return $string;}
}
?>
I then call the function from within the form using:
<td><select name="State"><option value="">Choose a State</option><?php showOptionsDrop($states_arr, null, true); ?></select></td>
Not sure what I'm missing but would love any assistance if somebody sees the error in my code.
Thanks!
Have a look at the code:
<?php showOptionsDrop($states_arr, null, true); ?>
You are passing null, so $active will always be null. The condition
($active == $k)
will never we evaluate to true.
You should pass the value you get from the form instead, e.g.:
<?php showOptionsDrop($states_arr, isset($fields['State']) ? $fields['State'] : null, true); ?>
You really should try to separate the PHP from the HTML, especially in your first example
Update:
Actually it is not that much, but consider to use the alternative syntax for control structures:
<select name="DOB3">
<optgroup label="Year">
<?php for ($i=date('Y'); $i>=1900; $i--) : ?>
<option value="<?php echo $i ?>"
<?php echo ($fields["DOB3"] == $i) ? 'selected="selected"' : '' ?> >
<?php echo $i ?>
</option>
<?php endforeach; ?>
</optgroup>
</select>
Also if you want to give the options some kind of label, you can do this with the optgroup HTML tag (this is not selectable).
Related
I need to select value dynamically using PHP in drop down list but in my case its not working as expected. I am explaining my code below.
<?php
$citySelected = "";
if(!isset($_GET['city'])){
$citySelected = 'selected="selected"';
}
?>
<select id="selectedLoc" name="selectedLoc" class="chosen-select form-control">
<option value="">Select City</option>
<option value="0" <?php echo $citySelected; ?>>Global</option>
<?php
foreach ($locationArr as $key => $value) {
$id = $value['id'];
$city = $value['city'];
$location = $value['location'];
$selected = "";
if(isset($_GET['city']) && $_GET['city']== $value['id']) {
$selected ='selected="selected"';
}
echo "<option value='$id' $selected>$location</option>";
}
?>
</select>
Here I need when there is any query string value then it will match with respective id and select that option and if there is no query string value at all then the global option will select.
Inside if condition ';' is missing. It should be like
if(isset($_GET['city']) && $_GET['city']== $value['id']){echo ' selected="selected"';}else{echo '';}
You can also use conditional operator for code simplicity, eg:-
<?php echo (isset($_GET['city']) && $_GET['city']== $value['id'])? ' selected="selected"':''; ?>
I have a select box that when the page loads it sets a value selected based upon a variable. I also have 2 IF statements that checks the variable and returns the results. Here is my code I am trying to do:
<select id="satbreak1" name="satbreak1">
<?php if ($trimmed_title[0] == "Guest")
{
echo ('<option selected value="#">Select One</option>');
echo ('<option value="y">Yes</option>');
echo ('<option value="n">No</option>');
}
if ($trimmed_title[0] != "Guest")
{
echo ('<option <?php if($trimmed_satBreakfast[0] == "") echo ("selected ") ; ?> value="#">Select One</option>');
echo ('<option <?php if($trimmed_satBreakfast[0] == "y") echo ("selected ") ; ?> value="y">Yes</option>');
echo ('<option <?php if($trimmed_satBreakfast[0] == "n") echo ("selected ") ; ?> value="n">No</option>');
}
?>
</select>
What I need to do is if $trimmed_title[0] == "Guest" then echo out the first part, but if $trimmed_title[0] != "Guest") then echo out the second part and also check what the status of $trimmed_satBreakfast[0] is and set the selected value.
What is the best / correct way to handle this?
The first part works fine but having an php script in a echo seems to fail.
I think this might do the trick - not tested but theoretically looks ok
<select id="satbreak1" name="satbreak1">
<?php
if ( $trimmed_title[0] == "Guest" ) {
echo '
<option selected value="#">Select One</option>
<option value="y">Yes</option>
<option value="n">No</option>';
} else {
$tsb=$trimmed_satBreakfast[0];
echo '
<option selected value="#" '.( $tsb=='' ? 'selected' : '' ).'>Select One</option>
<option value="y" '.( $tsb=='y' ? 'selected' : '' ) .'>Yes</option>
<option value="n"'.( $tsb=='n' ? 'selected' : '' ).'>No</option>';
}
?>
</select>
Something like this:
<?php
$options = array(
'values' => array('', 'y', 'n'),
'titles' => array('Select One', 'Yes', 'No')
)
$index = $trimmed_title[0] == 'Guest' ? 0 : array_search($trimmed_satBreakfast[0], $options['values']);
//if ($index === false) $index = 0;
$optHtml = array();
foreach($options['values'] as $i => $val) {
$selected = $index == $i ? 'selected' : '';
$optHtml[] = "<option $selected value=\"$val\">{$options['titles'][$i]}</option>";
}
$optHtml = implode("\n", $optHtml);
?>
<select id="id" name="name">
<?php echo $optHtml?>
</select>
or any other style to split html from php:
//if ($index === false) $index = 0;
...
?>
<select id="id" name="name">
<?php foreach($options['values'] as $i => $val) {?>
<option <?=$index==$i?'selected':''?> value="<?=$val?>">
<?=$options['titles'][$i]?>
</option>
<?php } ?>
</select>
In this case HTML not used in the common php code, but php used in HTML (only general template features: loop through data and echo it).
Common purpose of this is possibility to extract template part to separate file.
It is already PHP so you have to remove the php tags
echo ('<option '.($trimmed_satBreakfast[0] == "") ? : '"selected"' : ''.' value="#">Select One</option>');
echo ('<option '.($trimmed_satBreakfast[0] == "y") ? : '"selected"' : ''.' value="y">Yes</option>');
echo ('<option '.($trimmed_satBreakfast[0] == "n") ? : '"selected"' : ''.' value="n">No</option>');
I have a this html:
<option value="yes">Yes</option>
<option value="no">No</option>
and my php:
<?php
exec('uci get sms_gateway.setting.filter',$filt);
echo '<form action='.$_SERVER['PHP_SELF'].' method="post">
<select name="filter">';
foreach ($filt as $value){
if ($filt = "yes"){
echo '<option value="'.$value.'" selected>Yes</option><br>
<option value="no">No</option><br>ini yes';}
else {
echo '<option value="yes">Yes</option><br>
<option value="'.$value.'" selected>No</option><br> ini no';
}
}
echo '
</select>
<input type="submit" name="submit" value="Submit">';
if(isset($_POST['submit'])){
{
$data = $_POST['filter'];
echo "<br>halo ". $data;
}
}
?>
the $filt only has one string it's either yes or no
when it's yes I want the yes part on the dropdown menu selected, but when it's no I want the no part on the dropdown selected. How should I do that?
This bit of code:
foreach ($filt as $value) you're doing as $value so use:
foreach ($filt as $value){
if ($value == "yes"){
Then you have 2 sets of braces which are not needed; they're just extra keystrokes for nothing:
if(isset($_POST['submit'])){
{
$data = $_POST['filter'];
echo "<br>halo ". $data;
}
}
Change it to:
if(isset($_POST['submit'])){
$data = $_POST['filter'];
echo "<br>halo ". $data;
}
Another thing I spotted, a missing closing </form> tag.
Just for the record, you were also assigning using a single = sign, instead of comparing using two == for:
if ($filt = "yes")
which theoretically should have read as
if ($filt == "yes")
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
There's many things wrong with your code, you're treating "$filt" as both an array and a value, you're also assigning (=) instead of comparing. I'll give you a working example instead of trying to fix your code:
<?php $possibleValues = array('yes', 'no'); // All possible options ?>
<?php $valueYouWantSelected = 'yes'; // 'yes' will be selected ?>
<select>
<?php foreach ($possibleValues as $value): ?>
<?php $selected = ($valueYouWantSelected == $value) ? 'selected' : null; // Select this option if it equals $valueYouWantSelected ?>
<option value="<?php echo $value;?>" <?php echo $selected; ?>>
<?php echo $value; ?>
</option>
<?php endforeach ?>
</select>
If you're confused about how I assign $selected, check out ternary operators.
Also, I'm using alternative syntax, it makes it easier to organize PHP code within HTML (and colors code properly in your editor).
i am selecting an entry from the database to be edited on php/html. i can call the values of a table from the database and put it in a multiple tag.
$job_exp_tags = $row[16];//value from another table
$job_tags = explode(',',$job_exp_tags);//array to be put "selected" on the multiple select tag
$sql_2 = "SELECT _id, job_name from job_tags";
$sel_2 = mysql_query($sql_2);
$array = array();
while($row_new = mysql_fetch_assoc($sel_2)){
$array[] = $row_new;
}
<tr>
<td>Job Experience:<br>
(Hold ctrl to select multiple)</td>
<td><select name = 'job_tags[]' multiple>
<?php
foreach($array as $value){ ?>
<option value ='<?php echo $value['_id']; ?>'> <?php echo $value['job_name']; ?> </option>
<?php
}
?>
</select> </td>
</tr>
my problem is how can i put selected values to it from the explode statement
edit:
i've solved the problem, thanks anyway guys!
<option value ="<?php echo $value['_id']; ?>" <?php echo in_array($value['_id'], $job_tags) ? 'selected="true"' : null; ?>><?php echo $value['job_name']; ?></option>
Just check if its in your array, if so, set it selected:
foreach($array as $value){ ?>
$selected = in_array($value, $job_tags) ? ' selected ' : '';
/* Or [selected="selected"] if you dont use html5 yet (which you should) */
<option value ='<?php echo $value['_id']; ?>' <?php echo $selected; ?>> <?php echo $value['job_name']; ?> </option>
<?php
}
Your code can be simplified though:
foreach($array as $value){
$selected = in_array($value, $job_tags) ? ' selected="selected" ' : '';
?>
<option value="<?=$value['_id']?>" <?=$selected?> > <?=$value['job_name']?> </option>
<?php
}
I changed the quotes arround the value to doubles, not really a rule, but it is a good practice to do so. The other change is the short echo. Small demo, both do the same:
<php $var = 'foorbar'; ?> <!-- A bit weird, but this is demo-purpose -->
<span><?php echo $var; ?></span>
<span><?=$var?></span>
You could look for the value in the string $job_exp_tags and if found set the selected property.
foreach($array as $value){
$selected = strpos($job_exp_tags, $value) ? 'selected' : '';
echo '<option value="'.$value['_id'].'" '.$selected.'>'.$value['job_name'].'</option>';
}
I've got a few select lists on my form which look a bit like this:
<option value="400000" <?php if($_GET['MaxPrice'] == "400000") { echo("selected"); } ?>>£400,000</option>
As you can see (above) I've got a bit of PHP in there telling the form to remember it's selection upon submit.
Is there a short bit of PHP that would remember every selection without the rather heavy method I'm using above?
UPDATE:
<select name="MaxPrice" id="MaxPrice">
<option value="9999999" selected>Price (Max)</option>
<option value="100000" <?php if($_GET['MaxPrice'] == "100000") { echo("selected"); } ?>>£100,000</option>
<option value="200000" <?php if($_GET['MaxPrice'] == "200000") { echo("selected"); } ?>>£200,000</option>
<option value="300000" <?php if($_GET['MaxPrice'] == "300000") { echo("selected"); } ?>>£300,000</option>
<option value="400000" <?php if($_GET['MaxPrice'] == "400000") { echo("selected"); } ?>>£400,000</option>
</select>
UPDATE 2: Is there a way to implement this technique into some JavaScript?
if (BuyRent=='buy')
document.SearchForm.MaxPrice.options[9999999]=new Option("Price (Max)","150000000");
document.SearchForm.MaxPrice.options[100000]=new Option("\u00A3100,000","100000");
document.SearchForm.MaxPrice.options[200000]=new Option("\u00A3200,000","200000");
document.SearchForm.MaxPrice.options[300000]=new Option("\u00A3300,000","300000");
document.SearchForm.MaxPrice.options[400000]=new Option("\u00A3400,000","400000");
Usually, you use some kind of loop. Here's an example :
$my_values = array(100000, 200000, 300000, 400000);
foreach($my_values as $value) {
echo "<option value=\"{$value}\"";
echo ($_GET['MaxPrice'] == $value) ? 'selected="selected"';
echo ">" . number_format($value, 0, '.', ',') . "</option>";
}
Which would print 4 tags such as <option value="100000" selected="selected">100,000</option>.
This code also uses the ternary operator, but it's obviously not mandatory, you can write the whole if/else statement if wanted.
Edit:
<select name="MaxPrice" id="MaxPrice">
<option value="9999999">Price (Max)</option>
<?php
$my_values = array(100000, 200000, 300000, 400000);
foreach($my_values as $value) {
echo "<option value=\"{$value}\"";
echo ($_GET['MaxPrice'] == $value) ? 'selected="selected"' : "";
echo ">£ " . number_format($value, 0, '.', ',') . "</option>";
}
?>
</select>
good question, it made me wonder if there exists a js plugin to remember form field out there.
And the answer seems to be "Yes!"