Skip to content
Advertisement

Default to an option on a dropdown option

I’m trying to get a dropdown menu to default to a certain value depending on an employee number, I have managed to get it to say it but it’s not the right option as the options are pulled in from on MS SQL server, so it just created 2 options for ‘Labour’ for example, there’s the one from SQL which works but then one that’s created as it’s a default option but then it doesn’t let me post the form properly.

JavaScript

Shows that the option 'Labour' is created

Then the option 'Labour' appears again

Labour 2 is from the SQL server, which is the one I need it to default to so that I can use it to write back to the database. Otherwise, it thinks that that drop down is not set.

All help is appreciated cheers.

Advertisement

Answer

Just output selected="selected" for the default option.

I removed the useless concatenations for clarity, and used $selected as a variable to separate concerns. Of course you may want to organize the code differently, and change the test $costOption == 'Labour'.

JavaScript

If you never encountered it, (condition) ? X : Y is the ternary operator. If condition is true, X is chosen, otherwise Y is chosen.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement