Pre-populating and compare select field with 'selected' option - php

I am pulling form data from home.php into results.php and using $_GET['xxxxx'] to pre-populate fields of another form. I can populate input fields okay, but how would you compare an option field and $sale_type to selected if equal?
home.php
<form action="results.php" method="GET">
<input id="address" name="address" type="text" class="form-control1"/>
<select type="text" name="sale_type" placeholder="Sale Type">
<option value="Sale">For Sale</option>
<option value="Rent">To Rent</option>
</select>
<input name="submit" type="SUBMIT" value="Next" class="form-control1">
</form>
results.php
Option fields are already populated to ensure the form will work if it's used without results from home.php. I need to compare $sale_type value with the option of name="sale_type and if equal change that option value to selected.
$address = $_GET['address'];
$sale_type = $_GET['sale_type']; ?>
<form method="POST">
<input id="address" name="address" type="text" value='<?php echo $address; ?>'>
<select type="text" name="sale_type" placeholder="Sale Type">
<option value="Sale">For Sale</option>
<option value="Rent">To Rent</option>
</select>
<button type="submit" id="filter">Search</button>
<input type="hidden" name="action" value="ek_search">
</form>
What I'd like results to do
$address = $_GET['address'];
$sale_type = $_GET['sale_type']; ?> //If value is Sale
<form method="POST">
<input id="address" name="address" type="text" value='<?php echo $address; ?>'>
<select type="text" name="sale_type" placeholder="Sale Type">
<option value="Sale" selected>For Sale</option> //Change to selected if equal
<option value="Rent">To Rent</option>
</select>
<button type="submit" id="filter">Search</button>
<input type="hidden" name="action" value="ek_search">
</form>

You could check and then marked as selected when condition satisfy. One of the example is :
<option value="Sale" <?php if(condition) echo "selected" ?> >For Sale</option>

You'd compare the variable to value in the option tag like so:
<option value="Sale" <?= ($sale_type === 'Sale') ? 'selected' : ''; ?>>For Sale</option>
Another, option, if you will, is to set an array of sale_types. Instead of checking each individual option value, you could loop through the options and check there. Like this:
$sale_types = [
'Sale' => 'For Sale',
'Rent' => 'To Rent',
'SomeOtherType' => 'Something Else'
];
Then in select element:
<? foreach ($sale_types as $sale_value => $sale_option): ?>
<option value="<?= $sale_option; ?>" <?= ($sale_type === $sale_option) ? 'selected' : ''; ?>><?= $sale_value; ?></option>
<? endforeach; ?>

If you're going to do very much of this at all, my recommendation is to build a PHP function. Otherwise, you end up with a bunch of mixed HTML / PHP to check conditions.
This allows you to set up and display a dropdown quickly any time you need to.
Something like this would do what you want and would be re-usable:
// Function to generate the HTML for a select
function dropdown_array( $name, $value, $array, $placeholder = '' ) {
$temp_input = '<select name="' . $name . '"';
$temp_input .= ( $placeholder ) ? ' placeholder="' . $placeholder . '"' : '';
$temp_input .= '>' . PHP_EOL;
if ( is_array( $array ) ) {
foreach ( $array as $val => $text ) {
$temp_input .= '<option value="' . $val . '"';
if ( $value === $val ) {
$temp_input .= ' selected';
}
$temp_input .= '>' . $text . '</option>' . PHP_EOL;
}
}
$temp_input .= '</select>' . PHP_EOL;
return $temp_input;
}
Then, in your situation, usage would look like so:
$array = array( 'Sale' => 'For Sale', 'Rent' => 'To Rent' );
echo dropdown_array( 'sale_type', $sale_type, $array, 'Sale Type' );

Related

While filling in a form only update the form do not reload the whole page

I have got the following form:
<form action="" method="get" target="_self">
<select name="Category" class="dropmenu" id="Category"onchange="this.form.submit()">
<option value="">Any</option>
<option value="Keyboard"<?php if ($_GET['Category']=="Keyboard") {echo "selected='selected'"; } ?>>Keyboard</option>
<option value="Piano"<?php if ($_GET['Category']=="Piano") {echo "selected='selected'"; } ?>>Piano</option>
</select>
<select name='Manufacturer' class="dropmenu" onChange="this.form.submit()" >
<?php
echo '<option value="">Any</option>';
while ($row = mysql_fetch_array($RS_Search1)) {
$selected = $_GET['Manufacturer'] == $row['Manufacturer'] ? 'selected' : '';
echo '<option '.$selected.'>' . $row['Manufacturer'] . '</option>';
} ?> </select>
<select name="Color" class="dropmenu" onChange="this.form.submit()">
<?php
echo '<option value="">Any</option>';
while ($Color = mysql_fetch_array($RS_Search2)) {
$selected2 = $_GET['Color'] == $Color['Color'] ? 'selected' : '';
echo '<option '.$selected2.'>' . $Color['Color'] . '</option>';
} ?> </form>
Second form to submit
<form action="search2.php" method="get"> </select><input name="Category" type="hidden" value="<?php echo $_GET['Category']; ?>">
<input name="Manufacturer" type="hidden" value="<?php echo $_GET['Manufacturer']; ?>">
<input name="Color" type="hidden" value="<?php echo $_GET['Color']; ?>">
<select name="price" class="dropmenu">
<?php
echo '<option value="">Any</option>';
while ($Price = mysql_fetch_array($RS_Price)) {
$selected3 = $_GET['price_range'] == $Price['price_range'] ? 'selected' : '';
echo '<option '.$selected3.'>' . $Price['price_range']. '</option>';
} ?>
</select><input name="Search2" type="submit" id="Search2" value="Submit">
</form>
As you can see the option values are pulled from a db, after the first value is chosen. What the form does at the minute is reload the whole page. Is there a way to just reload the form in stead of reloading the whole page. I need to keep the values that are submitted on change of a option value to be able to fill in the next drop down menu.
Any help welcome.

Default option selected from SQL query in drop-down list

I want to have a drop-down list have a default value akin to how you would have value="abc" in a text field or similar. The only caveat is that I would like it to be defaulted to where an SQL query points it to. Excuse the long code.
//prior code where table and `foreach()` loop begins
<td>
<input type="text"
value="<?php echo $var["author"]; ?>"
required="required">
</input>
</td>
<td>
<select name="condition"
value="<?php echo $var["condition"]; ?>"
<option>M</option>
<option>NM</option>
<option>E</option>
<option>G</option>
<option>P</option>
</select>
</td>
//subsequent code where table is closed
For the first half, I have a text field of default value $var["author"], because that is what I query before beforehand. For the second, I can't seem to get the same result, due to it being a drop-down menu instead of a text field. If the .sql query brings up "NM", the default value will be "M", always. Any way to do this?
What you want is this:
//prior code where table and `foreach()` loop begins
<td>
<input type="text"
value="<?php echo $var["author"]; ?>"
required="required">
</input>
</td>
<td>
<select name="condition">
<option value="M"<?php echo ($var["condition"] == 'M' ? ' selected="selected"' : ''); ?>>M</option>
<option value="NM"<?php echo ($var["condition"] == 'NM' ? ' selected="selected"' : ''); ?>NM</option>
<option value="E"<?php echo ($var["condition"] == 'E' ? ' selected="selected"' : ''); ?>E</option>
<option value="G"<?php echo ($var["condition"] == 'G' ? ' selected="selected"' : ''); ?>G</option>
<option value="P"<?php echo ($var["condition"] == 'P' ? ' selected="selected"' : ''); ?>P</option>
</select>
</td>
//subsequent code where table is closed
or more elegant:
$dropdownOptions = array('N', 'NM', 'E', 'G', 'P');
//prior code where table and `foreach()` loop begins
<td>
<input type="text"
value="<?php echo $var["author"]; ?>"
required="required">
</input>
</td>
<td>
<select name="condition">
<?php foreach ($dropdownOptions AS $option) {
echo '<option value="' . $option . '"' . ($var["condition"] == $option ? ' selected="selected"' : '') . '>' . $option . '</option>';
} ?>
</select>
</td>
//subsequent code where table is closed

List Box Should be Drop down

to every one
I have some values in my data base i Want to display them with check boxes.
those values should be display when i click at the button. This should not in combo box.
because I want to post multiple values at one time.
Please help with thanks
<?php
$womenlist=mysql_query("select * from tbl_cycleduraion where user_id=$_SESSION[user_id]");
$gs=0;
while($girlslist=mysql_fetch_array($womenlist))
{
$gs++;
?>
<li style="background-color:#CCC; width:150px;"><label for="chk1"><input type="checkbox" name="chk_<?php echo $gs?>" id="chk<?php echo $gs?>" value="<?php echo $girlslist['calName'];?>" <?php if($_REQUEST['chk_'.$gs]==$girlslist['calName']){?> checked="checked"<?php }?>><?php echo $girlslist['calName']." ".$girlslist['calDesc']; ?> </label></li>
<?php }?>
You could limit the number of columns in your query (not SELECT * ...). You've put the <input> inside the <label>. The <label>'s for="" attribute is hardcoded as chk1. You could take out the inline style="" on the <li> and put it into a stylesheet. I've "tidied" it up a bit (untested):
$womenlist = mysql_query("select * from tbl_cycleduraion where user_id=$_SESSION[user_id]");
$gs = 0;
while( $girlslist = mysql_fetch_array($womenlist) )
{
$gs++;
echo '<li style="background-color:#CCC; width:150px;">'
. '<label for="chk' . $gs . '">' . $girlslist['calName'] . ' ' . $girlslist['calDesc'] . '</label>'
. '<input type="checkbox" name="chk_' . $gs . '" id="chk' . $gs . '" value="' . $girlslist['calName'] . '"
. (($_REQUEST['chk_'.$gs]==$girlslist['calName']) ? 'checked="checked"' : '') . '></li>';
}
Not sure entirely what you're asking for here (as it looks like you already have this working with checkboxes), but you can in fact post multiple values with a select box. You just use the multiple attribute, and specify the name as an array with the square brackets:
<form action="yourscript.php" method="post">
<select name="women[]" multiple="multiple">
<option value="woman1_name">Woman 1</option>
<option value="woman2_name">Woman 2</option>
<option value="woman3_name">Woman 3</option>
</select>
<input type="submit" />
</form>
If you post a form with this, selecting woman 2 & 3, var_dump($_POST); yields:
array(1) {
["women"]=>
array(2) {
[0]=>
string(11) "woman2_name"
[1]=>
string(11) "woman3_name"
}
}
Alternatively, if you want the values of your checkboxes to come through in a similar fashion, change them so they all have the same name, but with the square brackets on the end. This HTML would yield similar POST data:
<input type="checkbox" name="women[]" value="Woman 1" />
<input type="checkbox" name="women[]" value="Woman 2" />
<input type="checkbox" name="women[]" value="Woman 3" />
So, to create a dropdown using this, here's an adaptation of your code. I believe this is what you're after:
<?php
$options = '';
$womenlist=mysql_query("select * from tbl_cycleduraion where user_id=$_SESSION[user_id]");
while($woman=mysql_fetch_array($womenlist)) {
$options .= '<option value="'.$woman['calName'].'"'.((!empty($_REQUEST) && in_array($woman['calName'],$_REQUEST['women'])) ? ' selected="selected"' : '').'>'.$woman['calName'].' '.$woman['calDesc'].'</option>';
}
?>
<label for="women">Women:</label>
<select id="women" name="women[]" multiple="multiple">
<?php echo $options; ?>
</select>

How to preselect drop down choices and checkbox options in a form (PHP/MySQL)?

I am creating an update form where previously submitted information from a mysql database is grabbed to populate the current form. So this is what I have so far:
$select = mysql_query("SELECT * FROM some_table WHERE id = $id");
while ($return = mysql_fetch_assoc($select)) {
$name = $return['name'];
$bio = $return['bio'];
$maritalStatus = $return['marital_status'];
$favFood = $return['fav_food'];
}
<form action="page.php" method="post">
Name: <input type="text" name="name" value="<?php echo $name; ?>" /><br />
Bio: <textarea name="bio"><?php echo $bio; ?></textarea><br />
Marital Status
<select name="maritalStatus">
<option>Select One</option>
<option value="married">Married</option>
<option value="single">Single</option>
<option value="divorced">Divorced</option>
</select><br />
Favorite Food:
Cheeze: <input type="checkbox" name="favFood" value="cheeze" />
Cake: <input type="checkbox" name="favFood" value="cake" />
Oranges: <input type="checkbox" name="favFood" value="oranges" />
</form>
As you can see I am able to display data that was entered via an input text box or textarea just fine. But How to I have the "Marital Status" drop down preselected to the "divorced" option and the "Oranges" check box checked under "Favorite Food" GIVEN that those two choices are the ones that actually exist in the database?
Or, to avoid adding an if to each option, just do something like:
echo '<select name="maritalStatus">';
$status = array("Select one", "Married", "Single", "Divorced");
foreach($status as $s)
{
$sel = ($maritalStatus == $s) ? 'selected = "selected"' : '';
echo '<option value="'.$s.'" '.$sel.'>'.$s.'</option>';
}
echo '</select>';
EDIT:
To dynamically populate the select from the DB you could:
echo '<select name="maritalStatus">';
$res = mysql_query("SELECT status FROM marital_status");
while ($row = mysql_fetch_array($res))
{
$s = $row['status']
$sel = ($maritalStatus == $s) ? 'selected = "selected"' : '';
echo '<option value="'.$s.'" '.$sel.'>'.$s.'</option>';
}
echo '</select>';
<option value="single" <?php if($_REQUEST['maritalStatus'] == 'single'): ?>selected="selected"<?php endif ?>>Single</option>
And yes, you have to do an if for every option.
To preselect an option within in select you have to set the selected attribute like this:
<option value="married"<?= $marital_status == "married" ? ' selected="selected"' : ''?>>Married</option>
<option value="single"<?= $marital_status == "single" ? ' selected="selected"' : ''?>>Single</option>
<option value="divorced"<?= $marital_status == "divorced" ? ' selected="selected"' : ''?>>Divorced</option>
UPDATE
Or more DRY:
<?php foreach(array("married","single","divorced") as $status)): ?>
<option value="<?php= $status ?>"<?php $martial_status == $status ? ' selected="selected"' : '' ?>>
<?php= ucwords($status) ?>
</option>
<?php endforeach; ?>
Check Boxes
<input type="checkbox" id="id" name"checkbox" value="Option 1" checked>
or
<input type="checkbox" id="id" name"checkbox" value="Option 1" checked="checked">
Selection
<option value="Option 1" selected>Option 1</option>
or
<option value="Option 1" selected="selected">Option 1</option>
Conditional Selection
An example using jsp, where optionString is the variable to compare:
<input type="checkbox" id="id" name"checkbox" value="Option 1"
<%=(optionString.equalsIgnoreCase("Option 1"))? "checked":""%> />

Trouble pre-populating drop down and textarea from MySQL Database

I am able to successfully pre-populate my questions using the following code: First Name: <input type="text" name="first_name" size="30" maxlength="20" value="' . $row[2] . '" /><br />
However, when I try to do the same for a drop down box and a textarea box, nothing is pre-populated from the database, even though there is actual content in the database. This is the code I'm using for the drop down and textarea, respectively:
<?php
echo '
<form action ="edit_contact.php" method="post">
<div class="contactfirstcolumn">
Prefix:
<select name = "prefix" value="' . $row[0] . '" />
<option value="blank">--</option>
<option value="Dr">Dr.</option>
<option value="Mr">Mr.</option>
<option value="Mrs">Mrs.</option>
<option value="Ms">Ms.</option>
</select><br />';
?>
AND
Contact Description:<textarea id = "contactdesc" name="contactdesc" rows="3" cols="50" value="' . $row[20] . '" /></textarea><br /><br />
It's important to note that I am not receiving any errors. The form loads fine, however without the data for the drop down and textarea fields.
Thanks!
Tony
Select doesn't work that way.
If you want to pre populate select, you can try this way:
$predata = array(
'blank' => '--',
'Dr' => 'Dr.',
'Mr' => 'Mr.',
'Mrs' => 'Mrs.',
'Ms' => 'Ms.',
);
echo "<select name='prefix'>";
foreach($predata as $value => $label){
echo "<option value='$value' ".($value == $row[0] ? 'selected="selected"' : '').">$label</option>";
}
echo "</select>";

Categories