View Full Version : dynamic select_options trouble

03-04-2008, 09:12 PM
Hey All,
Trying to dynamicaly generate options for a predefined select named MSA.
The following works... sort of -- insofar as I manage to generate at least one option,
but if there are more matches of ($state_abrev and $parr[3]) I still get only one option -- (that from the first match).
Please, what am I doing wrong here?

foreach($msa_stats as $parr){
if(preg_match("/$state_abrev/i", $parr[3])) {
echo "<script>
var opts=document.forms['get_MSA'].MSA.options;
for (i=0;i<opts.length;i++){
opts[i] = new Option('$parr[2]','$parr[2]');

03-04-2008, 10:02 PM
You probably want to revise the way you build the Javascript to only echo one beginning script tag and assign the variable opts only once. Then inside your foreach() you should echo the Javascript code that adds a new option, and make sure the iterator variable you use (the variable "i") doesn't get set back to zero each time a match is found. Instead you should add 1 to i each time a match is found. I think...

03-05-2008, 12:44 AM
Thanks Fumigator,

Took me a bit, but I got it!

$get_msa = "<script>var opts=document.forms['get_MSA'].MSA.options;for (i=0;i<opts.length;i++){ ";
foreach($msa_stats as $parr){
if (preg_match("/$state_abrev/i", $parr[3])) {
$get_msa = "$get_msa"."opts[i++] = new Option('$parr[2]','$parr[2]'); ";
$get_msa.= '}</script>';
echo $get_msa;Surprised to discover that concatenation ($get_msa.=)would not work within the confines of the foreach, so I worked around it.:D