blarg
blarg

Reputation: 3893

How to set default value for HTML drop-down list not from the option element?

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?

Upvotes: 3

Views: 12037

Answers (3)

Ronald Swets
Ronald Swets

Reputation: 1667

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>

Upvotes: 4

chopss
chopss

Reputation: 811

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);

Upvotes: 2

Simon Shirley
Simon Shirley

Reputation: 328

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.

Upvotes: 2

Related Questions