3

I'm using an adaptation of PHPBB to create a drop-down list.

  <select name="destination_path">
    <!-- BEGIN path -->
    <option value="{path.DESCRIPTION}">{path.DESCRIPTION}</option>
    <!-- END path -->
  </select>

The list is generated from a MySQL query, so it is dynamic. This list is within a form and when the form is fired I want to retain (and return) it's state in session variables. My first thought was to place something in the <select> statement.

I know you can use:

selected="option_selected" 

in the relevant <option>, but it seems like a messy way to do this and would require an if statement to compare each tag as the tag is created.

Is there a way to declare the default option in the select tag, or a better defined method to achieve the same result?

3 Answers 3

4

Short answer: No.

The select tag defines the selected option in its option elements. What you could do if you want to achieve it differently, is putting the selected option on top without specifying a selected attribute. Most browsers select the first option as default if there is no selected attribute present.

Ex :
 <select>
 <option value="Hi"> Hi </option>
 <option value="Hello" selected> Hello </option>
 </select>
Sign up to request clarification or add additional context in comments.

2 Comments

That would work, but would it not affect the order the list is presented?
@blarg Yes, it would.
2

You may be able to select the option you need after compiling the list by adding a little jQuery.

A similar question has been asked on the jQuery Forums.

Using the example of:

<select name="options">
  <option value="1">Red</option>
  <option value="2">Green</option>
  <option value="3">Blue</option>
</select>

You can set the selected option by value:

$('[name=options]').val( 3 ); // To select Blue

Or you can set the selected option using the text:

$('[name=options] option').filter(function() { 
    return ($(this).text() == 'Blue'); //To select Blue
}).prop('selected', true);

Links to jsFiddle can be found in this post.

Credit to: Godsbest on the jQuery Forums.

Comments

2

Yes.... there is a way to declare the default option in the select tag

Try this...

To set a default value first you have to mention the name of the select tag and in the find() function just pass the value you have to set as default value.

$('select[name="destination_path"]').find('option:contains("default")')
.attr("selected",true);

1 Comment

Please, care to add some comment or explanation. Pasting just a few lines of code isn't to warm welcome here.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.