Jump to content

[SOLVED] Blank option and double selected items in dropdown


richrock

Recommended Posts

As the title says.  I've got a list of countries (and also cities) from a DB, populated them into a set of dropdowns (I haven't chained them yet, but going to).

 

I have a twofold problem.

 

1: The dropdown adds a blank entry just under the '-- Select Country --' option.  Why?  How can I make this disappear?

 

2: I have used an 'if' statement to get the selected country to remain as the option.  But because of problem #1 - if I haven't got a country selected, it decides to select the blank one, not the '-- Select Country --'

 

I have mucked around with this for quite a bit, but getting nowhere - and very fast.

 

If I can solve #1 I'm sure I can resolve issue #2.

 

    echo "<tr><td>";
    ?>
<select name="country" id='inputtext' onchange="this.form.submit();" >
                <?php
                echo "<option value=''";
                if ($country == NULL) {
                    echo " selected";
                }
                echo ">-- Select Country --</option>";
                ?>
				<?php
					do {
                        if ($row_country['country'] == $country) {
                            echo "<option value = '".$row_country['country']."' selected >".$row_country['country']."</option>";
                        } else {
			echo "<option value='".$row_country['country']."'>".$row_country['country']."</option>";
                        }
                //}

				} while (($row_country = mysql_fetch_assoc($rcountry)) != NULL) ;
					$rows = mysql_num_rows($rcountry);
					if($rows > 0) {
					mysql_data_seek($rcountry, 0);
					$row_country = mysql_fetch_assoc($rcountry);
					}
				?>
		</select><?php
    echo "</td></tr>";

 

and the mysql db query, just in case:

 

$getcountry = "SELECT DISTINCT country FROM yearbook ORDER BY country ASC";
$rcountry = mysql_query($getcountry) or die(mysql_errno() . mysql_error());
$row_country = mysql_fetch_assoc($rcountry);
$tRows_country = mysql_num_rows($rcountry);

 

Could it be I need to include a IS NOT NULL in the DB query (if so, that's a mysql issue and I'm posting in the wrong place)...

You're trying to reference some things in the wrong order...try replacing your code with this:

<select name="country" id="inputtext" onchange="this.form.submit();" >
<option value="">-- Select Country --</option>
<?php
while ($row_country=mysql_fetch_assoc($rcountry)) {
  echo '<option value="'.$row_country['country'].'"'.($row_country['country']==$country ? ' selected' : '').'>'.$row_country['country'].'</option>';
}
?>
</select>
?>
</td></tr>

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.