Jump to content

Dropdown menu php


fortnox007

Recommended Posts

Hi all, I was wondering if someone knows a clean way to make a dropdown menu using just php and html with the following functionality. If someone selects a value from the dropdown options it should be visible on refresh.

So in case a have a dropdown menu with: oranges, apples, grapes and someone selects grapes and submits it, grapes should be selected.

 

I have made someonthing but it looks redundant. I think there should be something with a foreach loop or something but i can't figure it out yet.

 

Thanks in advance,

cheers!!

Link to comment
Share on other sites

Hi there,

 

Something like this:-

 

function Offset(){
$OffsetGap = range('0','24', '2');

$OffsetHtml = "<select name=\"Choose_offset\">";
$OffsetHtml .= "<option value=\"".(isset($_POST['Choose_offset']) ? $_POST['Choose_offset'] : '')."\">".(isset($_POST['Choose_offset']) ? $_POST['Choose_offset'] : 'Choose offset')."</option>";
foreach($OffsetGap AS $OffsetGapKey=>$OffsetGapValue){
	$OffsetHtml .= "<option value=\"".$OffsetGapValue."\">".$OffsetGapValue."</option>";
}
$OffsetHtml .= "</select>";

return $OffsetHtml;

}

 

I can't be bothered re doing this for you, but this is something that I use for something similar to what you are asking for, it seems to work, just adjust it according to your needs. Have fun.

 

Cheers,

Rw

Link to comment
Share on other sites

That is way more complicated than it needs to be.

 

The key is to have a defined "list" of values. This can be from a database query or from a hard-coded array. Here is a simple example:

$optionList = array('apple', 'orange', 'banana', 'pear');
$fruitOptions = '';
$selectedValue = (isset($_POST['fruit'])) ? $_POST['fruit'] : false;
foreach($optionList as $value => $label)
{
    $selected = ($value == $selectedValue) ? 'selected="selected"' : '';
    $fruitOptions .= "<option value=\"{$value}\"{$selected}>{$label}</option>\n";
}

 

Then where you have the select list in the body of your page

<select name="fruit">
<?php echo $fruitOptions; ?>
</select>

Link to comment
Share on other sites

Oh wow thanks you both for the really quick respond. the first one looks pretty advanced  :o I have to decypher it a bit but that's good for learning. I'll try to rewrite it a bit with normal if-statements (i still have to learn alot :) The second looks more easier for my brains :)

Thanks alot guys!

Link to comment
Share on other sites

I could see what you were after, and this is the closest thing that I have to had without rewriting something, and to be honest I haven't got that much time, I am at work after all.

 

Good source of inspiration this place when you get stuck!

 

@mjdamato: I didn't realise that it was overkill, it suits my need, though this is an old example from something I did a while back - I just though that it scratched the itch :)

 

Cheers,

Rw

Link to comment
Share on other sites

I'll try to rewrite it a bit with normal if-statements

 

Why would you not want to use the ternary operator? It is the perfect solution when you need to set a variable to one of two values based upon a condition.

 

Here is the same code with comments added

//Array of values for the select list
$optionList = array('apple', 'orange', 'banana', 'pear');
//Variable to hold the html for the options
$fruitOptions = '';
//Assign the selected value (if it was set)
$selectedValue = (isset($_POST['fruit'])) ? $_POST['fruit'] : false;
//Iterrate through each option (uses the index key as the actual value)
foreach($optionList as $value => $label)
{
    //Set the $selected variabled based on whether the selcted option equals the current option
    $selected = ($value === $selectedValue) ? 'selected="selected"' : '';
    //Add the html for the current option to the options variable
    $fruitOptions .= "<option value=\"{$value}\"{$selected}>{$label}</option>\n";
}

EDIT: Made one change. Changed the double equal to a triple equal. The reason for doing so is that I set the $selectedValue to false if the POST value was not set. The problem was that if there is an option with a value of 0, then false would compare to 0 using double equal comparison. This isn't a problem with this particular example since 0 would be the first value. But, if there was a situation where 0 could be the 2nd or later option, then that value would be preselected even if the user did not submit a value.

 

@mjdamato: I didn't realise that it was overkill, it suits my need, though this is an old example from something I did a while back - I just though that it scratched the itch :)

 

I think it was overkill in the sense that there was more going on than just preselecting a value. I suspect offset gap part of the code would cause more confusion than clarification.

Link to comment
Share on other sites

Why would you not want to use the ternary operator? It is the perfect solution when you need to set a variable to one of two values based upon a condition.

Well i am still kinda new to this way of writting php.

 

In both your codes i see complete new things for me:

- variables within {}

-  .=

- something that looks like an if statements with ? and :

 

Lol this small script will keep me bussy studying : ) Anyways ty both for the great help

-edit : Ill try to learn those things today : )

Link to comment
Share on other sites

Hi there fortnox007,

 

- variables within {}

 

This just means that he hasn't used concatenations for adding things into a string, could be achieved with double quotes and a . period.

 

-  .=

 

This is a method of building a variable, literally meaning add to

 

- something that looks like an if statements with ? and : (called a ternary operator)

 

This is just doing an if/else statement without using multiple lines of code, this will be your best friend in the world of php - I use them where ever I can, and nested ones are brilliant, though that's for another day.

 

Hope that's clarified a few things for you anyway.

 

@mjdamato: Yes, thinking about it I could have removed those parts - wasn't exactly clear there, but I was hoping that the example could have been 'modified' to suit his needs

 

Cheers,

Rw

 

Link to comment
Share on other sites

Oh a small questions i have about the {} i just tested a bit and foudn out {} cant be used within single quotes but only within double quotes.

 

But In the book I have it says that i can use variables in a double quoted string without using the special dots which are needed in a single quoted string. So to make it clear for my self; why are you using:

$fruitOptions .= "<option value=\"{$value}\"{$selected}>{$label}</option>\n";

instead of

$fruitOptions .= "<option value=\"$value\"$selected>$label</option>\n";

 

i hope this isn't the most stupid question, but it totally new for me

Link to comment
Share on other sites

Hi there,

 

I guess it's down to preference.

 

I would have done this:-

$fruitOptions .= "<option value=\"".$value."\"$selected>".$label."</option>\n\r";

 

But all of this will do the same thing:

 

$fruitOptions .= "<option value=\"{$value}\" {$selected}>{$label}</option>\n";

//Single quote's means that you don't need to escape the doubles
$fruitOptions .= '<option value="$value" '.$selected.'>'.$label.'</option>\n';

$fruitOptions .= "<option value=\"".$value}."\" ".$selected.">".$label."</option>\n";

 

I think I have that correct anyway

 

Just so that there is a clear divide between php & html

 

Cheers,

Rw

Link to comment
Share on other sites

Oh a small questions i have about the {} i just tested a bit and foudn out {} cant be used within single quotes but only within double quotes.

 

You might want to have a look at the PHP manual for strings: http://php.net/manual/en/language.types.string.php

 

Basically, when you use double quotes (or the heredocs method) to define a string, the PHP parser will interpret variables within the string. Here are a couple of examples:

$foo = 'bar';

//Double quotes
echo "The value is $foo";
//Output: The value is bar

//Single quotes
echo 'The value is $foo';
//Output: The value is $foo

 

See the difference? When using variables within quotes I always use the curly braces. The braces help to avoid problems where the variable may be misinterpreted within the string. Examples:

$foo = 'bar';
$array['index'] = 'somevalue';

echo "Variable adjacent to other 'text': $foo_underscore";
//Ouptut: Variable adjacent to other 'text': 
//The PHP is trying to parse the variable $foo_underscore which doesn't exist

echo "Variable adjacent to other 'text': {$foo}_underscore";
//Ouptut: Variable adjacent to other 'text': bar_underscore
//The curly braces define where the variable begins and ends for the PHP parser

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.