Listbox Selected Value being Repeated

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
NotOnUrNelly
Forum Commoner
Posts: 61
Joined: Wed Mar 24, 2004 4:45 pm

Listbox Selected Value being Repeated

Post by NotOnUrNelly »

HI all,

I have a list box that has the permanent numbers 0 - 9. I simply want to maintain the selected value once the form is submitted. I plan to have a test on the form that looks for fields that are not completed.

The listbox at the moment is produced using an if statement. If the variable is not set the list box produces 0-9 and is fine.

If the form has been submitted and a variable is sent to the listbox. It manages to show the correct selected value, but when the list box is expanded again that value is repeated 10 times instead of having 0 - 9 the value (say 3) is repeated in the list box.

Here is my code hope someone can help.

Many Thanks
Jamie

print "<SELECT NAME=Q1a value=0>";
for ($i=0; $i<10; $i++){
if (isset ($Q1a))
{
print "<OPTION value =$i selected>$Q1a</OPTION>";
}
else
{
print "<OPTION value=$i>$i</OPTION>";
}
}

print "</SELECT><br><br>";
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

My diagonisis is "your code is bad".
Have you read what you wrote?

Code: Select all

print "<SELECT NAME=Q1a value=0>";
for ($i=0; $i<10; $i++){
    if (isset ($Q1a)) {
        print "<OPTION value =$i selected>$Q1a</OPTION>";
    } else {
    print "<OPTION value=$i>$i</OPTION>";
    }
}
print "</SELECT><br><br>";
Anyway this is what you want:

Code: Select all

echo '<select name="q1a">';
for ($i=0; $i<10; $i++) {
    echo '<option value="' . $i . '"';
    if (isset($Q1a) and $Q1a == $i) {
        echo ' selected="selected"';
    }
    echo '>'. $i . '</option>';
}
NotOnUrNelly
Forum Commoner
Posts: 61
Joined: Wed Mar 24, 2004 4:45 pm

Post by NotOnUrNelly »

Hi Jason,

That worked a treat many thanks for your help.

Jamie
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

Jason?
I'm not Jason :) sorry.
NotOnUrNelly
Forum Commoner
Posts: 61
Joined: Wed Mar 24, 2004 4:45 pm

Post by NotOnUrNelly »

Sorry that was the reply on my email must be the admin guy.

Thanks Again I was messing with that for ages
Post Reply