Forum Moderators: coopster

Message Too Old, No Replies

adding selected="yes" based on url / GET data

         

mr_nabo

10:58 am on Mar 24, 2010 (gmt 0)

10+ Year Member



Hi,

Is there any way to automatically make an option in a drop-down list 'active' based on the URL?

I'm pulling information from a MySQL database by using GET['dropdown'] to retrieve the variables. When someone selects something from a dropdown and submits my form, I want the dropdown to 'remember' what my user has selected.

I assume I need to use the url which contains the $_GET variables and it would be something like this:

<?php
$dropdown = $_GET['dropdown'];
if($dropdown == 'firstoption') { echo 'selected="yes"'; }
if($dropdown == 'secondoption') { echo 'selected="yes"'; }
if($dropdown == 'thirdoption') { echo 'selected="yes"'; }
?>


But is there a better way to not have to echo out each option? I have quite a few dropdowns with lots of options...

Any ideas?

Thanks,

mn

Anyango

11:01 am on Mar 24, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



imho thats the only option available, what you are doing is good already.

Matthew1980

11:08 am on Mar 24, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi both,

A switch would be useful in this context I think...

Cheers,
MRb

astupidname

11:40 am on Mar 24, 2010 (gmt 0)

10+ Year Member



Tossing arrays around a bit usually helps lighten such code when there will be a bit much to deal with:
<?php

//a listing of expected values for $_GET['dropdown'] field:
$a = array('firstoption', 'secondoption', 'thirdoption');
$a2 = array_flip($a); //keys become values, values become keys

$selectionText = 'selected="selected"'; //selected="yes" is incorrect
$dropdown = 'thirdoption';//$_GET['dropdown'];
$makeSelectedIndex = (isset($a2[$dropdown])) ? $a2[$dropdown] : 0; //defaults to 0
echo 'When your loop counter gets to: '.$makeSelectedIndex.' or thereabouts, then echo $selectionText in the option';

?>

I guess I am assuming you are echoing out options in a loop or something, so that's what that is based on, determining which option to echo the 'selected' attribute on.
Hope that helps or gives more ideas!

[edited by: astupidname at 11:42 am (utc) on Mar 24, 2010]

Readie

11:41 am on Mar 24, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



What I do here is use a array and a loop.

$dropdown = $_GET['dropdown'];

$drop_values = array(
array('value_one', 'text_one'),
array('value_two', 'text_two'),
array('value_three', 'text_three')
);

$drop_menu = '<select name="something">';

foreach($drop_values as $drop) {
if($drop[0] === $dropdown) {
$sel = ' selected="selected"';
} else {
$sel = '';
}
$drop_menu .= "\n" . '<option value="' . $drop[0] . '"' . $sel . '>' . $drop[1] . '</option>';
}
$drop_menu .= "\n" . '</select>';

Anyango

11:57 am on Mar 24, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Although the aray idea is good, but imo if your selects are not with too many options, its essentialy the same amount of typing involved, maybe even more. i would rather simply echo "selected" within the option itself than first creating the array and then running a loop. But the idea is surely good as suggested by all of the above, and will work if your list of options is too long.

Readie

12:50 pm on Mar 24, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Very very easy to add additional options to the select menu with my array method however, whereas directly echoing the "selected" takes a bit longer.

If you only have 2/3 options and it's impossible you're ever going to change the page then yeah, echo the selected directly, otherwise it's worth taking the extra time now to save regrets later.

---

If you have multiple option menus that you want to generate and (optionally) remember their selected values, you could create a custom function:

function select_build($options_array, $select_name, $mem_info = '') {
$output = '<select name="' . $select_name . '">';
foreach($options_array as $option) {
if(isset($mem_info) && $mem_info != "") {
if($mem_info === $option[0]) {
$sel = ' selected="selected"';
} else {
$sel = '';
}
} else {
$sel = '';
}
$option .= "\n" . '<option value="' . $option[0] . '"' . $sel . '>' . $option[1] . '</option>';
}
$output .= "\n" . '</select>';
return $output;
}

Then just prepare an array in the way I referenced in my previous post and call it as:
$drop_menu = select_build($drop_values, 'something', $_GET['dropdown']);

You can leave the $_GET out if you don't wish to remember the value - it'll work the same if you change it to $_POST too, or even just a static value.

Anyango

2:26 pm on Mar 24, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



whereas directly echoing the "selected" takes a bit longer.


How? Most of the times we make things too complicated in search for "a little bit less time". Although optimization is good, but it cant be the justification for any undue complication imho. Has anybody computed the milliseconds and bechmarked processor quantums it takes to do both things seperately ? I would love to know how fast it is in comparison to an echo.

Cheers :)

Readie

2:34 pm on Mar 24, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



by "takes a bit longer" I meant to manually add into the code :P

Anyango

2:45 pm on Mar 24, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Coool :)

rocknbil

7:05 pm on Mar 24, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



whereas directly echoing the "selected" takes a bit longer.
.... I would love to know how fast it is in comparison to an echo.


There is another aspect to this - echoing as you go - that becomes extremely relevant when you have large pages. This is true of **any** language. In the context of this "project" it's irrelevant, but a good habit to get into (as we know, habits are hard to break . . . )

On one hand you are freeing up memory by echoing/outputting as you run. This used to be an issue in the days when we had to sip at memory, today, even on shared servers, the amount of memory used but the scalar storage methods, in even a huge page output, is more likely to choke the browers than a server.

When you begin to deal with pages of this magnitude, in admin interfaces, reports, stuff like that, what you get is a page that renders a header . . .

. . . then a little content . . .

. . . then some more . . .

. . . and eventually finishes.

By storing as a scalar, it makes for a more graceful GUI, and eventually leads to good coding via functions. Compile your output, echo once. My version of outputting selects, coded for HTML 4/5 (XHTML needs selected="selected"):


$drop_values = array(
'value_one' => 'text_one',
'value_two' => 'text_two',
'value_three' => 'text_three'
);
//
$dropdown = (isset($_GET['dropdown']))?$_GET['dropdown']:NULL; // :-P
$onchange=NULL; // could be ' onchange="some_javascript(this);"';
$class=NULL; // styling
//
$select = get_my_select('something',$drop_values,$dropdown,$class,$onchange);
//
echo '<form action=""><label for="something">Some Thing:</label> ' . $select . '</form>';
//
//
function get_my_select($name,$values,$val,$style,$actions) {
//
if ($class) { $class = " class=\"$class"\"; }
//
$drop_menu = "<select name=\"$name\" id=\"$name\"" . $class . "$actions>\n";
foreach ($values as $key=>$value) {
$drop_menu .= "option value=\"$key\"";
if ($val == $key) { $drop_menu .= " selected"; }
$drop_menu .= ">$value</option>\n";
}
$drop_menu .= "</select>\n";
return $drop_menu;
}

[edited by: rocknbil at 7:09 pm (utc) on Mar 24, 2010]

Readie

7:09 pm on Mar 24, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Just pointing out a typo in rocknbil's coding above:

foreach ($values as $key=>$value) {

Should be

foreach ($drop_values as $key=>$value) {

rocknbil

7:22 pm on Mar 24, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Incorrect. :-) $drop_values is out of scope of the function, and is passed as a parameter, received by the function:

$select = get_my_select('something',$drop_values,$dropdown,$class,$onchange);

function get_my_select($name,$values,$val,$style,$actions) {

I do have an error, though. Part of using form controls as they are intended relies on implementing them properly. It's good practice to always have an empty/null at the top of a select. This prevents them from accidentally submitting something they didn't intend, and makes for asier error checking (if (select_value='') { error; }

$drop_menu = "<select name=\"$name\" id=\"$name\"" . $class . "$actions>
<option value="">Select</option>\n";

[edited by: rocknbil at 7:27 pm (utc) on Mar 24, 2010]

Readie

7:27 pm on Mar 24, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Ahh yes, my bad. Ignore me.

Sorry :P

mr_nabo

10:09 am on Mar 25, 2010 (gmt 0)

10+ Year Member



Thanks for all your replies, it's been interesting seeing how you all approach this - I'll use the array approach for larger projects, but for this one I think it makes sense to simply echo out selected="selected" for each option (there are quite a few options, but not enough to warrant an array I think).

Cheers

rocknbil

7:23 pm on Mar 25, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Well, consider one thing.

Do you use other select drop down lists in your program? Or do these select values come from a database? In either case this is to your advantage.

One function, any list, any name, and any number of potential values.

I had a few small errors before, here's a working freebie demonstration . . .


<?php
header("content-type:text/html");
$drop_values = array(
'value_one' => 'text one',
'value_two' => 'text two',
'value_three' => 'text three'
);
$another_list = array(
'1' => 'A One An',
'2' => 'A Two An',
'3' => 'A Three Ana'
);
//
$dropdown = (isset($_GET['dropdown']))?$_GET['dropdown']:NULL; // :-P
$onchange=NULL; // could be ' onchange="some_javascript(this);"';
$class=NULL; // styling
//
$select = get_my_select('something',$drop_values,$dropdown,$class,$onchange);
$js = ' onchange="alert(this.options[this.selectedIndex].value);"';
$select2 = get_my_select('something-else',$another_list,'',$class,$js);
//
echo '<form action="">
<label for="something">Some Thing:</label> ' . $select . '
<label for="something-else">Something Else:</label> ' . $select2 .
'</form>';
//
//
function get_my_select($name,$values,$val,$style,$actions) {
//
if ($class) { $class = " class=\"$class\""; }
//
$drop_menu = "<select name=\"$name\" id=\"$name\"" . $class . "$actions>
<option value=\"\">Select</option>\n";
foreach ($values as $key=>$value) {
$drop_menu .= "<option value=\"$key\"";
if ($val == $key) { $drop_menu .= " selected"; }
$drop_menu .= ">$value</option>\n";
}
$drop_menu .= "</select>\n";
return $drop_menu;
}
?>