Link To Specific Option Values - php

I am trying to modify some code I found on this site (courtesy of mqchen) to enable linking to specific option values. Although it's close to what I'm looking for, I have little php knowledge and therefore need some help. Here's the original code:
<?php
$options = array('Norway', 'United States', 'Springfield');
echo '<select>';
foreach($options as $country) {
if(array_key_exists('selected', $_GET) && $_GET['selected'] === $country) {
echo '<option selected="selected">'.$country.'</option>';
}
else {
echo '<option>'.$country.'</option>';
}
}
echo '</select>';
?>
And the link would be something like:
/countries.html?country=norway
I need to have not only the country between the option tags, but also a value in the option tag, so that the final output would be:
<option value="unitedstates">United States</option>
I was also going to edit the third line to:
echo '<select name="name" size="1" onchange="ShowHide(this.value);">';
because my select tag currently has those attributes for certain functionality. So basically all I need to do, I believe, is add another array containing the option values that line up with the countries and put the variable into the option tag, which I assumed would be:
<option value="'.$valueid.'">
But I'm not exactly sure.

You should do
$options = array('norway' =>'Norway', 'unitedstates' => 'United States', 'springfield' => 'Springfield');
echo '<select name="name" size="1" onchange="ShowHide(this.value);">';
foreach($options as $key => $country) {
if(array_key_exists('selected', $_GET) && $_GET['selected'] === $country) {
echo '<option selected="selected" value="'.$key.' >'.$country.'</option>';
}
else {
echo '<option value="'.$key.'>'.$country.'</option>';
}
}
echo '</select>';
BTW - this is php not jQuery

Related

Get all values of option fields and push it into an array

Let's say I have a photo upload system where the user have to set a category for each album to get the basics for a nice and clean search functionality. But if an user is changing now a value like this:
<select>
<option value="">Choose a Category</option>
<option value="Holiday">Holiday</option>
</select>
to this:
<select>
<option value="">Choose a Category</option>
<option value="Holiday">Something Stupid</option>
</select>
is "something stupid" entered into the database.
That's why I have to do a server side check. But I don't know how to get all the correct values of the option fields to compare it with the posted value.
So my first considerations were the following:
PHP:
// Get all values of the option fields
// Push all the values into an array
if (in_array('foo', $array)) {
// foo is in the array
}
Thank you for helping.
Ok, so I think I guessed what you tried to tell.
You should not have the tags hardcoded in your list.php file, but instead have an array there. That way, you can use it both for generating the select field, but also for the verification. However, generally a database table with the categories would be preferable.
path/list.php
return array(
'1' => 'Name of Ctg 1',
'2' => 'Name of Ctg 2'
);
Here you generate the select
<select name="whatever">
<?php
$options = include('path/list.php');
foreach($options as $id => $name) {
echo '<option value="' . $id . '">' . $name . '</option>';
}
?>
</select>
And how to verify it then in the "target" page
$options = include('path/list.php');
if(!array_key_exists( $valueFromUser, $options ) ) {
// invalid option
}
When the data is posted from the page containing the select tag, it will be in the $_REQUEST array, if you run this php in catcher php page:
foreach ($_REQUEST AS $key => $value) echo "$key = $value <br>";
you will see the results from your list.php.

How to do a pre-select drop down in PHP with added description?

I liked the function contributed here:
PHP - PRE-select drop down option
function generateSelect($name, $options, $optionToSelect) {
$html = '<select name="'.$name.'">';
foreach ($options as $option => $value) {
if($value == $optionToSelect)
$html .= '<option value="'.$value.'" selected="selected">'.$value.'</option>';
else
$html .= '<option value="'.$value.'">'.$value.'</option>';
}
$html .= '</select>';
return $html;
}
/* And then call it like */
$html = generateSelect('company', $companies, 'Apple');
However, this doesn't address a description that is needed sometimes with drop-down menu.
For example:
<select name="ranges">
<option value="0">All Ranges</option>
<option value="1">Under $10,000</option>
<option value="2">$10,000 - $25,000</option>
<option value="3">$25,000 - $50,000</option>
<option value="4">$50,000 - $75,000</option>
<option value="5">$75,000 - $100,000</option>
<option value="6">$100,000 - $200,000</option>
<option value="7">$200,000 or more</option>
</select>
What needs to be modified for the generateSelect function to allow it to assign, for example, along with a value of "4", but a description of "$75,000 - $100,000" to accompany it? The way the generateSelect function is now, it would assign a value of "4" and place in the description (for lack of a better term) also a "4".
Or is there a better way to do this in PHP? Thanks!
I am not sure what you mean by description (perhaps you could clarify; do you want an additional attribute that contains the option key? I am unregistered so I cannot ask except as an answer)
If you want for example to show the "description" as part of the value attribute, you would simply append it to the value attribute like so:
$html .= '<option value="'.$value.' ('.$option.')" selected="selected">'.$option.'</option>';

Getting variables in jquery mobile via PHP

I have an issue getting variables using PHP in a tablet site I have been working on. I have a search form on the homepage that passes variables to a list page. I then have the same search form in a 'refine search' dialog box which should pre-select the appropriate values depending on what has been passed, using PHP.
The problem is I can't seem to get the variables that have been passed (using PHP). For example I have this field in my search:
<select name="propertyType" id="propertyType">
<option value="">Any Type</option>
<option value="1"<?php if(isset($_GET['propertyType']) && $_GET['propertyType']=="1") { echo ' selected'; } ?>>Houses</option>
<option value="2"<?php if(isset($_GET['propertyType']) && $_GET['propertyType']=="2") { echo ' selected'; } ?>>Flats/Apartments</option>
<option value="3"<?php if(isset($_GET['propertyType']) && $_GET['propertyType']=="3") { echo ' selected'; } ?>>Bungalows</option>
<option value="4"<?php if(isset($_GET['propertyType']) && $_GET['propertyType']=="4") { echo ' selected'; } ?>>Other</option>
</select>
But when I pass any of these values my code does not pick them up and echo the relevant 'selected'.
The tablet site can be found here: http://muskermcintyre.co.uk/tablet Any help would be much appreciated!
Thanks.
I suggest you following syntax:
<?php
$values = array(
0 => 'Any Type',
1 => 'Houses',
2 => 'Flats/Apartments',
3 => 'Bungalows',
4 => 'Other'
);
$current = (int) $_GET['propertyType'];
?>
<select name="propertyType" id="propertyType">
<?php
foreach ( $values as $key => $value ) {
$selected = $key == $current ? 'selected="selected"' : '';
echo "<option value='$key' $selected >$value</option>";
}
?>
</select>
I've had a similar problem in the past and got round it by getting the query string using Javascript/jQuery.
A quick search gave me this which might help you if you go down a similar route:
How can I get query string values in JavaScript?

how to keep the choosed data in the <select> element? HTML

here I have stupid question, hope you can help me.
I create a menu using Select element and option like this:
<option selected="selected">Select type...</option>
<option value="1">Doctor</option>
<option value="2">Patient</option>
and every time I need to pick one value from this menu and use the submit button next to it to transfer data.
But every time the page refreshed, this menu will reveal: Select type...
I want it to reveal the value I chose last time, but don't know how.
Many thanks in advance!!
You'll want to move that selected="selected" onto the selected option.
Doing so in PHP isn't too rough. Just check the $_POST or $_GET (however you sent the form) value for your select box, such as $_POST["selectBox"] for each value down the list. When you find a match, echo out the selected="selected" string there. If the value was empty, output it on your default value.
The easiest way to achieve this is to populate the <select> options in an array, then loop through it to display the <option> list and mark them as selected is the $_POST variable matches the correct value:
<?php $myselect = array(1=>'Doctor', 2=>'Patient'); ?>
<select name="myselect">
<option>Select type...</option>
<?php foreach ($myselect as $value => $label): ?>
<option value="<?php echo $value; ?>"<?php if (isset($_POST['myselect']) && $_POST['myselect'] == $value) echo ' selected'; ?>>
<?php echo $label; ?>
</option>
<?php endforeach; ?>
</select>
<select name="myselect">
<?php
$myselect = array('Select type...','Doctor','Patient');
for($i=0; $i<=2; $i++){
echo "<option value=\"{myselect[$i]}\"";
if (isset($_POST['myselect']) && $_POST['myselect'] == $myselect[$i]){
echo 'selected=\"selected\"';
}
echo ">{$myselect[$i]}</option>";
}
?>
</select>
You have to use the server-side language of you choice to store the selected value in a database, xml or text file.
Edit : I think I may have misunderstood your question.
There are a few ways to do this.
On submit you can save that value as a $_SESSION value and use that to set the select on page load.
Using Javascript you can either set a cookie on change or alter the url to add a parameter (url?selecttype=1) and set that on page load using PHP.
There's a good use of cookies in JS on quirksmode: http://www.quirksmode.org/js/cookies.html
You need to change which one is selected to match the request....
function create_select($properties, $opts)
{
$out="<select ";
foreach ($properties as $propname=>$propval) {
$out.=" $propname='$propval'";
}
$out.=">\n";
foreach ($opts as $val=>$caption) {
$out.="<option value='$value'";
if ($_REQUEST[$properties['name']]==$val) $out.=" SELECTED";
$out.=">$caption</option>\n";
}
$out.="</select>";
return $out;
}
print create_select(array('name'=>'direction',
'id'=>'direction',
'class'=>'colourful',
'onChange'=>''),
array('N'=>'North',
'S'=>'South',
'E'=>'East',
'W'=>'West'));

How can I add text into a certain area?

If I have a line like this,
<option value="someval">somval</option>
how can I position the cursor after the last quotation of value and put something like abcdef?
So the output would be
<option value="somval" abcdef>somval</option>
with PHP?
I want to do this dynamically and I can't figure out how to do it. I'm looking at strpos(), but I don't see how it can be done. I'll be posting a bunch of option tags into a textbox and code will be generated. so I'll have a lot of option fields.
#martin - Say I have a huge dropdown and each option lists a country that exists. Rather than having to manually type out something like this:
$query = $db->query("my query....");
while($row = $db->fetch($query)) {
<select name="thename">
<option value="someval" <?php if($row['someval'] == 'someval') { print "selected"; } ?> >someval</option>
<option value="someval" <?php if($row['someval'] == 'someval') { print "selected"; } ?> >someval</option>
<option value="someval" <?php if($row['someval'] == 'someval') { print "selected"; } ?> >someval</option>
... Followed by 100 more, because there are a lot of locations to list.
</select>
How can I post all the options I have into a textbox and have the above code automatically generated to save a lot of time?
Using your example you would do:
while($row = $db->fetch($query)) {
printf('<option value="someval"%s>someval</option>',
($row['someval'] == 'someval') ? ' selected="selected" ' : '');
}
This would go through the rows and output an option, replacing the %s with the attribute selected="selected" if $row['someval'] is equal to someval. However, the above is rather pointless, because all option elements will have the same value and text, so try
while($row = $db->fetch($query)) {
printf('<option value="%s"%s>%s</option>',
$row['country-code'],
($row['country-code'] === $selection) ? ' selected="selected" ' : '',
row['country-name']);
}
With $selection being anything you want to compare against. Replace the keys in $row with appropriate keys from in your database.
Note: The usual disclaimers about securing your output apply
You could capture (value=".+?") and replace it with $0 abcdef.
<?php
$string = '<option value="someval">someval</option>';
print preg_replace("/(value=\".+?\")/i", "$0 abcdef", $string);
?>
Which outputs the following:
<option value="someval" abcdef>someval</option>
With PHP, you can generate a whole string with any text you wish. Where do you have your original string? In a variable or a text file?

Categories