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>
Related
I have a database field country which I want to query and select that country option from a select element. Is there any way to do this without adding:
if (query->country == "<some country>"){echo "selected"}
in every single option tag? As there are hundreds of country options. Here is a little example of the code. Thank you.
$query = $query->fetch_object();
// which ever country is held in the variable `$query->country` should be selected
echo"<select>
<option>Afghanistan</option>
......
......
<option>Zimbabwe</option>
</select>";
Don't you have a list of all countries on your server?
$countries = ["Afghanistan", ... , "Zimbabwe"];
You could do something like this:
$selection = "Some country";
echo "<select>";
foreach($countries as $country)
{
if($country == $selection)
echo "<option selected>" . $country . "</option>";
else
echo "<option>" . $country . "</option>";
}
echo "</select>";
The IF still needs to be "placed" on every <option> but as a programmer you should do something like this:
$options = array( 'Afghanistan', '...', 'Zimbabwe' );
foreach( $options as $option )
{
$selected = ( $query->country == $option )? ' selected': '';
echo '<option' . $selected . '>' . $option . '</option>';
}
and if you're unfamiliar with ternary operator, the $selected = ... part above can be written like this:
if ( $query->country == $option )
{
$selected = ' selected';
}
else
{
$selected = '';
}
I have a country list of every country in a form to get a parcel quote.
When a user presses the "Get Quote" button, all the text forms retain the information previously entered using PHP.
How can I do this with the country list box? As I can't have PHP on every option checking if that is the country selected and adding "Selected" to the html.
Is there a better way other than generating the country list from a file in a loop?
EDIT:
Going for the method of looping through a file, and checking..
This is what I have so far:
$countries = fopen("includes/countries.txt", "r");
$countries = explode(";", $countries);
Then in the HTML:
<select id="countries" name="countries">
<?php
foreach ($countries as $country){
echo("<option value=\"" . $country . "\">" . $country . "</option>");
}
?>
</select>
Not yet finished.
I assume you have an array with your countries stored. You could try something like this:
$countries = array('Albania', 'Egypt');
$selected_country_id = $_GET['c_id']; // You may need to change this to match with your code
$country_selected = array();
foreach($countries as $country) {
if($country['id'] == $selected_country_id) {
$country_selected[ $country['id'] ] = ' selected ';
} else {
$country_selected[ $country['id'] ] = '';
}
}
Then, assuming that you dynamically add your Select-Options, do this:
// In your each-fn
echo '<option value="' . $country['id'] . '" ' . $country_selected[ $country['id'] ] . '>' . $country['name'] . '</option>';
Something like this would be better
foreach ($countries as $country) {
?>
<option value="<?php echo $country" <?php echo ($country == $_POST['country'] ? 'selected' : ''; ?>><?php echo $country; ?></option>
<?php
}
<select id="countries" name="countries">
<?php
foreach ($countries as $country){
if(isset($_POST["country"]) && $_POST["country"] == $country){
$sel = "selected";
}else { $sel= ""; }
echo("<option value=\"" . $country . "\"" .$sel.">" . $country . "</option>");
}
?>
</select>
Get All Country-State-City Selectbox ....!!!
See Link : GitHub
I've been trying to solve this problem for the last 3 hours and I'm getting close, but my inexperience is showing. I've tried all the permutations I can think of.
I have a form with checkboxes. The values are retrieved from mysql. The form is being submitted to the same page. You can view it live here. Type "Axminster" for the search.
The original checkbox code is as follows:
<?php
$categories_list = split('[
]', get_setting('categories', $db));
foreach ($categories_list AS $cat)
{
$cat = trim($cat);
echo "<input type=\"checkbox\" name=\"categories[]\" value=\"" . $cat . "\">" . $cat . "<br>";
}
?>
so I then submit the form and as normal I want the checkbox checked values to remain checked. For a dropdown box in my form I have used the code
<?php if($radius == $_POST['radius']) echo ' selected="selected"'; ?>
and this works perfectly, however I'm trying to use the following code to get the checked checkboxes to remain checked, and I'm having no luck:
<?php
$categories_list = split('[
]', get_setting('categories', $db));
foreach ($categories_list AS $cat)
{
$cat = trim($cat);
// I've added these two lines, and added " . $select . " to the input field.
foreach ($_POST['categories'] AS $category) {
if($cat == $category) { $select = "CHECKED"; } }
echo "<input type=\"checkbox\" " . $select . " name=\"categories[]\" value=\"" . $cat . "\">" . $cat . "<br>";
}
?>
The result is that every checkbox after the first checked checkbox is also being checked. For example I have four checkboxes and even if I check only the 2nd checkbox, the 3rd and 4th are also being checked on the next page.
I'm completely lost now. Please can anyone help. Thanks.
You could use
if(isset($_POST['categories']) && in_array($cat, $_POST['categories']))
You also need to reset the $select on each loop, or use an else{}, as once it is set using your foreach, the value never changes, so all checkboxes after the selected will be checked as well.
the code could now look like-
<?php
$categories_list = split('[
]', get_setting('categories', $db));
foreach ($categories_list AS $cat)
{
$cat = trim($cat);
// I've added these two lines, and added " . $select . " to the input field.
if(isset($_POST['categories']) && in_array($cat, $_POST['categories'])) { $select = "CHECKED"; }
else { $select = ''; }
echo "<input type=\"checkbox\" " . $select . " name=\"categories[]\" value=\"" . $cat . "\">" . $cat . "<br>";
}
?>
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.
I have a select box that shows 3 options: option1, option2, option3. When a user hits submit, then in $_POST I do have the value selected. Is there an easy way to redisplay the select box with the chosen option highlighted WITHOUT it being repeated in the options?
In other words, if option2 is selected and submit is clicked, the page should display again with option2 selected, and option1 and option 3 underneath.
Thanks.
<?php
$arrValues = array(...);
$selectedValue = (isset ($_POST['selectName']) ? $_POST['selectName'] : "");
?>
<select name="selectName">
<?php
for ($i = 0; $i < count($arrValues); $i++)
{
$opts = ($arrValues[$i] == $selectedValue) ? ' selected="selected"': '';
echo '<option value="' . $arrValues[$i] . '"' . $opts . '>' . $arrValues[$i] . '</option>';
}
?>
</select>
Create your options like this.
$options = array("optionvalue" => "Option Name");
foreach($options as $value => $name)
{
if(isset($_POST['select_box']))
{
if($_POST['select_box'] == $value)
{
echo '<option selected="selected" value="'.$value.'">'.$name.'</option>';
continue;
}
}
echo '<option value="'.$value.'">'.$name.'</option>';
}
When you generate the select box, use the POST data (if available) to pick the item that's selected (and/or to sort the items).
Kind of like:
if($_POST["optval"] == $opt) $sel = "selected='selected'"; else $sel = "";
print "<option value='$opt' " . $sel . ">$opt</option>";
Naturally you'd want to verify that the POST data is valid and that it exists (isset). Assuming of course that you generate your select box from data accessible by PHP, rather than statically define it.