By Jichao


2010-08-19 01:10:51 8 Comments

I thought that adding a "value" attribute set on the <select> element below would cause the <option> containing my provided "value" to be selected by default:

<select name="hall" id="hall" value="3">
  <option>1</option>
  <option>2</option>
  <option>3</option>
  <option>4</option>
  <option>5</option>
</select>

However, this did not work as I had expected. How can I set which <option> element is selected by default?

27 comments

@access_granted 2020-04-19 01:13:48

Upstream System:
<select name=upstream id=upstream>
<option value="SYBASE">SYBASE ASE
<option value="SYBASE_IQ">SYBASE_IQ
<option value="SQLSERVER">SQLSERVER
</select>
<script>
var obj=document.getElementById("upstream");
for (var i=0;i<obj.length;i++){if(obj.options[i].value==="SYBASE_IQ")obj.selectedIndex=i;}
</script>

@Borealid 2010-08-19 01:12:33

Set selected="selected" for the option you want to be the default.

<option selected="selected">
3
</option>

@Sree Rama 2013-03-19 07:42:12

<option value="3" selected="selected"> 3 </option> The value would be passed as a string when option 3 is selected.

@Sree Rama 2013-03-19 07:48:49

And keep continue using id attribute for <Select> and it is not good to use value attribute for <select> html element.

@MindJuice 2014-11-11 16:59:53

The ="selected" part is not necessary. Just <option selected> will do as mentioned in other answers.

@Borealid 2014-11-13 19:24:48

@MindJuice What I wrote is valid polyglot HTML/XML. Using <option selected> is okay for a browser, but may cause the document to be rejected by other parsers. I find it handy to be able to use XPath/XSLT on web documents occasionally.

@Apostle 2015-05-21 07:14:15

BTW, in all popular browsers you set a default value (a pre-selected option) also by using the value attribute for the <select> tag, i.e. <select value="3">, but it's not valid in the W3C validator.

@metakermit 2015-07-17 09:49:53

If you're using Angular, note that ng-model overrides the the default selected value (even as undefined if you did not set the bound object). Took me a while to figure that was why the selected="selected" option was not selected.

@user137717 2015-08-04 21:50:51

@kermit666 good tip. I was trying to set value='123' but i ended up setting the corresponding $scope vars in the controller to give a default value to the ng-model fields

@nclsvh 2015-12-28 14:08:47

How would you do this in a foreach loop? Lets say you populate the dropdown from an sql query, but you want the old value (for example on user edit page) to be set as default

@xDaizu 2016-02-15 09:43:21

@NicolasV The simplest way is: You save the old value in a variable and each loop iteration you check if the value of the loop is equal to the the saved value. If it is, you add selected="selected" to the output. :)

@Stefan Vasiljevic 2016-08-03 16:37:51

For AngularJS devs, you can use ng-init to initialize your model to the value you want selected.

@Uriah Blatherwick 2017-08-24 19:59:07

Yes, for Angular2/4+ it's good to ensure you are setting a value on the option like <option value='3' selected="selected" [(ngModel)]="mymodel" >3</option> and make sure you either initiliaze your model to that value in declaration or in the constructor. this.mymodel = '3'. I use this along with a blank value and the disabled attribute on my option to allow setting a default (effectively a watermark).

@Anomaly 2018-03-20 16:33:24

@Borealid While the XHTML thing is valid, I find using just <option [various attributes] selected> to be cleaner, since it is in reality a boolean property that is being set, not a string value.

@Borealid 2018-03-20 19:22:00

@Anomaly This answer is eight years old. It, and the comments about it, remain correct. You're free to use non-XML-compatible HTML if you wish.

@Fabien Snauwaert 2019-03-20 11:50:25

In Firefox, reloading the page will ignore whatever the default selected element is (which may cause you to think it's not working!) Simply force-reload the page to see the true default value.

@Pradip Vadher 2019-08-31 05:52:01

can anyone tell me how to set this in angular with ngmodel?

@Simon 2020-02-18 07:19:26

If Firefox overrides your pre-selected option element, turn autocomplete off, see stackoverflow.com/a/10096033/208746

@Ajay 2020-04-03 01:28:56

React: selected={true}

@finnmglas 2020-05-13 12:28:13

Why is this so much upvoted compared to other answers that are more precise?

@Akbor 2020-02-12 08:22:42

Set selected="selected" where is option value is 3

please see below example

<option selected="selected" value="3" >3</option>

@Mwspace LLC 2020-01-12 15:52:16

HTML snippet:

<select data-selected="public" class="form-control" name="role">
    <option value="public">
        Pubblica
    </option>
    <option value="user">
        Utenti
    </option>
    <option value="admin">
        Admin
    </option>
</select>

Native JavaScript snippet:

document.querySelectorAll('[data-selected]').forEach(e => {
   e.value = e.dataset.selected
});

@tebbe93 2019-10-27 11:30:01

You can try like this

  <select name="hall" id="hall">
      <option>1</option>
      <option>2</option>
      <option selected="selected">3</option>
      <option>4</option>
      <option>5</option>
    </select>

@upog 2019-09-03 16:34:45

I use Angular and i set the default option by

HTML Template

<select #selectConnection [(ngModel)]="selectedVal" class="form-control  col-sm-6 "  max-width="100px"   title="Select" 
      data-size="10"> 
        <option  >test1</option>
        <option >test2</option>      
      </select>

Script:

sselectedVal:any="test1";

@Michał Mielec 2019-02-16 19:10:59

Best way in my opinion:

<select>
   <option value="" selected="selected" hidden="hidden">Choose here</option>
   <option value="1">One</option>
   <option value="2">Two</option>
   <option value="3">Three</option>
   <option value="4">Four</option>
   <option value="5">Five</option>
</select>

Why not disabled?

When you use disabled attribute together with <button type="reset">Reset</button> value is not reset to original placeholder. Instead browser choose first not disabled option which may cause user mistakes.

Default empty value

Every production form have validation, then empty value should not be a problem. This way we may have empty not required select.

XHTML syntax attributes

selected="selected" syntax is the only way to be compatible with both XHTML and HTML 5. It is correct XML syntax and some editors may be happy about this. It is more backward compatible. I do not have strong feeling about this, but if above-mention arguments are your requirements you should follow full syntax.

@ADEL NAMANI 2020-01-04 16:17:41

That hides the whole option for me

@Michał Mielec 2020-01-07 20:06:45

@ADELNAMANI Could you provide the link to your code? I guess your problem is not related to my answer.

@Ambuj Khanna 2018-09-11 05:19:45

You just need to put attribute "selected" on a particular option instead direct to select element.

Here is snippet for same and multiple working example with different values.

   Select Option 3 :- 
   <select name="hall" id="hall">
    <option>1</option>
    <option>2</option>
    <option selected="selected">3</option>
    <option>4</option>
    <option>5</option>
   </select>
   
   <br/>
   <br/>
   <br/>
   Select Option 5 :- 
   <select name="hall" id="hall">
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option selected="selected">5</option>
   </select>
   
    <br/>
   <br/>
   <br/>
   Select Option 2 :- 
   <select name="hall" id="hall">
    <option>1</option>
    <option selected="selected">2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
   </select>

@Ahmedakhtar11 2018-09-04 08:02:35

I would just simply make the first select option value the default and just hide that value in the dropdown with HTML5's new "hidden" feature. Like this:

   <select name="" id="">
     <option hidden value="default">Select An Option</option>
     <option value="1">One</option>
     <option value="2">Two</option>
     <option value="3">Three</option>
     <option value="4">Four</option>
   </select>

@Jim 2018-07-07 15:34:12

The problem with <select> is, it's sometimes disconnected with the state of what's currently rendered and unless something has changed in the option list, no change value is returned. This can be a problem when trying to select the first option from a list. The following code can get the first-option the first-time selected, but onchange="changeFontSize(this)" by its self would not. There are methods described above using a dummy option to force a user to make a change value to pickup the actual first value, such as starting the list with an empty value. Note: onclick would call the function twice, the following code does not, but solves the first-time problem.

<label>Font Size</label>
<select name="fontSize" id="fontSize" onfocus="changeFontSize(this)" onchange="changeFontSize(this)">           
    <option value="small">Small</option>
    <option value="medium">Medium</option>
    <option value="large">Large</option>
    <option value="extraLarge">Extra large</option>
</select>

<script>
function changeFontSize(x){
    body=document.getElementById('body');
    if (x.value=="extraLarge") {
        body.style.fontSize="25px";
    } else {
        body.style.fontSize=x.value;
    }
}
</script>

@Samim Aftab Ahmed 2018-05-07 16:30:29

You can use:

<option value="someValue" selected>Some Value</option>

instead of,

<option value="someValue" selected = "selected">Some Value</option>

both are equally correct.

@Julian 2014-02-20 14:29:38

This code sets the default value for the HTML select element with PHP.

<select name="hall" id="hall">
<?php
    $default = 3;
    $nr = 1;
    while($nr < 10){
        if($nr == $default){
            echo "<option selected=\"selected\">". $nr ."</option>";
        }
        else{
            echo "<option>". $nr ."</option>";
        }
        $nr++;
    }
?>
</select>

@Johan 2017-11-23 08:12:22

If you are in react you can use defaultValue as attribute instead of value in the select tag.

@Akshay Vijay Jain 2017-11-08 06:48:35

If you are using select with angular 1, then you need to use ng-init, otherwise, second option will not be selected since, ng-model overrides the defaul selected value

<select ng-model="sortVar" ng-init='sortVar="stargazers_count"'>
  <option value="name">Name</option>
  <option selected="selected" value="stargazers_count">Stars</option>
  <option value="language">Language</option>
</select>

@ Юрий Светлов 2016-07-07 18:44:22

I myself use it

<select selected=''>
    <option value=''></option>
    <option value='1'>ccc</option>
    <option value='2'>xxx</option>
    <option value='3'>zzz</option>
    <option value='4'>aaa</option>
    <option value='5'>qqq</option>
    <option value='6'>wwww</option>
</select>

@Nobita 2015-05-29 09:05:34

In case you want to have a default text as a sort of placeholder/hint but not considered a valid value (something like "complete here", "select your nation" ecc.) you can do something like this:

<select>
  <option value="" selected disabled hidden>Choose here</option>
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
  <option value="4">Four</option>
  <option value="5">Five</option>
</select>

@chrisallick 2016-08-22 22:07:55

I would think this is what most people are looking for. Good answer.

@Nobita 2016-10-28 20:29:04

It was an external jsfiddle where the css was just needed not to make it appear along the border of the screen. After some months it got edited to an inline code snippet and the guy who edited simply kept it in the example. You can edit and remove it from the snippet if it really bothers you.

@Ivan Akulov 2017-08-13 02:04:55

An even better solution is to use the hidden attribute instead. See @chong-lip-phang’s answer below: stackoverflow.com/a/39358987/1192426

@user8202629 2017-08-25 06:20:13

<option value="" selected disabled hidden>Choose here</option>

@Michał Mielec 2019-02-16 19:19:45

IMHO disabled is not a good idea. Look at my answer: stackoverflow.com/a/54726699/4809490

@japes Sophey 2020-02-17 11:19:49

Awesome answer!

@Marc.2377 2020-08-27 00:55:48

If you have trouble getting this to work, try Ctrl+F5 to refresh the browser cache. Worked for me (Firefox 80.0).

@Chong Lip Phang 2016-09-06 22:59:39

I prefer this:

<select>
   <option selected hidden>Choose here</option>
   <option value="1">One</option>
   <option value="2">Two</option>
   <option value="3">Three</option>
   <option value="4">Four</option>
   <option value="5">Five</option>
</select>

'Choose here' disappears after an option has been selected.

@Bogdan Mates 2016-09-08 09:50:00

I tryed this but "Choose here" isn't displayed. The first option is empty

@Chong Lip Phang 2016-09-09 00:23:04

What browser are you using?

@Bogdan Mates 2016-09-09 06:39:02

I'm using Google Chrome browser version 52.0.2743.116 m

@Chong Lip Phang 2016-09-09 09:27:39

I am using that browser too and not experiencing any problem.

@Ryan Walton 2016-09-19 22:16:50

Consider adding value="" to assure you get an empty value.

@RedFilter 2010-08-19 01:12:02

Complete example:

<select name="hall" id="hall"> 
  <option> 
    1 
  </option> 
  <option> 
    2 
  </option> 
  <option selected> 
    3 
  </option> 
  <option> 
    4 
  </option> 
  <option> 
    5 
  </option> 
</select> 

@Rodrigo 2014-01-13 22:44:25

That's simpler than use selected="selected".

@ps2goat 2014-07-24 17:11:30

selected="selected" should work for all doctypes. XHTML doesn't like attributes without values.

@xDaizu 2016-02-15 09:41:04

@Rodrigo Is it really that difficult to write selected="selected"? I mean, what are you saving? Time? Size? It's negligible and if it makes the code more "compliant", why not doing it?

@Rodrigo 2016-02-15 14:18:47

@DanielParejoMuñoz, ok, it's negligible. But if my doctype is html, and not xhtml, why waste any byte at all?

@Clarence 2017-03-29 17:31:26

I think you should inspect your code if all you use is selected... I'm experiencing a situation right now where the selected default option is not changed in chrome when you choose another option

@Paul McCarthy 2017-06-08 20:49:21

selected="selected" looks like an error. In a couple of months I'd probably change it to selected="3" thinking that this means that item 3 is selected. (and break my page)

@Ilya Streltsyn 2017-10-02 13:59:07

Even if doctype claims it is XHTML, but the page is served with Content-type: text/html HTTP header, all browsers will parse it as HTML, treating selected as a boolean attribute and ignoring all "XML-compliant" features.

@Anomaly 2018-03-06 22:07:24

@xDaizu It's simpler, less confusing (why set a boolean value with a string attribute?), and prettier.

@Salitha Prasad 2016-06-05 15:54:03

An improvement for nobita's answer. Also you can improve the visual view of the drop down list, by hiding the element 'Choose here'.

<select>
  <option selected disabled hidden>Choose here</option>
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
  <option value="4">Four</option>
  <option value="5">Five</option>
</select>

@MindJuice 2014-11-11 15:47:37

I came across this question, but the accepted and highly upvoted answer didn't work for me. It turns out that if you are using React, then setting selected doesn't work.

Instead you have to set a value in the <select> tag directly as shown below:

<select value="B">
  <option value="A">Apple</option>
  <option value="B">Banana</option>
  <option value="C">Cranberry</option>
</select>

Read more about why here on the React page.

@Apostle 2015-05-20 15:40:14

You can set a pre-selected option in a drop-down list by using the value attribute for the <select> tag, i.e. <select value="3">, but it's not valid in the W3C validator.

@MindJuice 2015-05-20 22:15:21

Right, but this isn't HTML, it's JSX, so it doesn't need to follow W3C rules. The HTML generated by React in the end is valid though.

@Justus Romijn 2017-07-04 14:30:21

In a perfect world this had been a comment to the question, as it is not a valid answer. But I guess it has enough value to stick around.

@CDK 2018-01-11 14:46:06

I needed a similar solution to the above suggestion, but with JQuery instead of React. In case it helps anyone in the future: $("select").each(function(){ $(this).find('option[value="'+‌​$(this).attr("value"‌​)+'"]').prop('select‌​ed', true); });

@Aaron C 2020-05-13 13:42:26

This answer is not valid, the underlying question is talking about HTML not React (JSX).

@dc_Bita98 2020-08-27 14:17:21

If you're using Angular check this out

@X-Coder 2015-06-02 05:49:14

value attribute of tag is missing, so it doesn't show as u desired selected. By default first option show on dropdown page load, if value attribute is set on tag.... I got solved my problem this way

@Graeme 2014-01-07 13:02:29

I used this php function to generate the options, and insert it into my HTML

<?php
  # code to output a set of options for a numeric drop down list
  # parameters: (start, end, step, format, default)
  function numericoptions($start, $end, $step, $formatstring, $default)
  {
    $retstring = "";
    for($i = $start; $i <= $end; $i = $i + $step)
    {
      $retstring = $retstring . '<OPTION ';
      $retstring = $retstring . 'value="' . sprintf($formatstring,$i) . '"';
      if($default == $i)
      {
        $retstring = $retstring . ' selected="selected"';
      }
      $retstring = $retstring . '>' . sprintf($formatstring,$i) . '</OPTION> ';
    }

  return $retstring;
  }

?>

And then in my webpage code I use it as below;

<select id="endmin" name="endmin">
  <?php echo numericoptions(0,55,5,'%02d',$endmin); ?>
</select>

If $endmin is created from a _POST variable every time the page is loaded (and this code is inside a form which posts) then the previously selected value is selected by default.

@tilak 2013-10-25 04:12:24

The selected attribute is a boolean attribute.

When present, it specifies that an option should be pre-selected when the page loads.

The pre-selected option will be displayed first in the drop-down list.

<select>
  <option value="volvo">Volvo</option>
 <option value="saab">Saab</option>
 <option value="vw">VW</option>
 <option value="audi" selected>Audi</option> 
</select> 

@AlexM 2013-10-19 22:33:44

This is how I did it...

<form action="../<SamePage>/" method="post">

<?php
    if ( $_POST['drop_down'] == "")
    {
    $selected = "";
    }
    else
    {
    $selected = "selected";
    }
?>

<select name="select" size="1">

  <option value="1" <?php $selected ?>>One</option>
     ////////  OR  ////////
  <option value="2" $selected>Two</option>

</select>
</form>

@Ryan 2013-11-27 07:17:06

There seems to be some incongruity to this solution. If the name of the element is "select", shouldn't the $_POST variable key be "select" -- where does "drop_down" come from? Also, assuming that was an error, and this is actually checking the $_POST['select'] variable for a value, any non-empty value will return true, and thus all <option> items will be marked "selected". Maybe I'm missing something integral to this answer?

@Florian 2013-10-16 20:36:45

if you want to use the values from a Form and keep it dynamic try this with php

<form action="../<SamePage>/" method="post">


<?php
    $selected = $_POST['select'];
?>

<select name="select" size="1">

  <option <?php if($selected == '1'){echo("selected");}?>>1</option>
  <option <?php if($selected == '2'){echo("selected");}?>>2</option>

</select>
</form>

@Ally 2013-09-17 06:37:26

Another example; using JavaScript to set a selected option.

(You could use this example to for loop an array of values into a drop down component)

<select id="yourDropDownElementId"><select/>

// Get the select element
var select = document.getElementById("yourDropDownElementId");
// Create a new option element
var el = document.createElement("option");
// Add our value to the option
el.textContent = "Example Value";
el.value = "Example Value";
// Set the option to selected
el.selected = true;
// Add the new option element to the select element
select.appendChild(el);

@7yl4r 2014-10-28 18:01:32

shouldn't that be el.selected = "selected"; to comply with the w3 standard?

@Ally 2014-10-31 04:34:53

@7yl4r No. selected is a boolean property as defined by w3c - w3.org/TR/html401/interact/forms.html ` 17.6.1 Pre-selected options selected [CI] - When set, this boolean attribute specifies that this option is pre-selected.` For more information on usage see w3c schools - w3schools.com/jsref/prop_option_selected.asp

@harmender 2012-07-03 19:39:36

You can do it like this:

<select name="hall" id="hall">
    <option> 1 </option>
    <option> 2 </option>
    <option selected> 3 </option>
    <option> 4 </option>
    <option> 5 </option>
</select> 

Provide "selected" keyword inside the option tag, which you want to appear by default in your drop down list.

Or you can also provide attribute to the option tag i.e.

<option selected="selected">3</option>

@htmldrum 2012-07-22 21:00:55

Just to be clear, the w3 standard is <option selected="selected">3</option>

@Juan Mendes 2013-01-15 17:39:53

@JRM I think what you mean is that if for your document to be XHTML compliant than an attribute must have a a value. In HTML there is no need for "selected=selected". The examples on w3.org/wiki/HTML/Elements/select, developer.mozilla.org/en-US/docs/HTML/Element/select do not specify a value. The important thing to note is that selected="false" is not allowed and selected="" also makes it selected. The only way to make an options not selected is to remove the attribute. w3.org/html/wg/drafts/html/master/…

@Phil 2018-03-03 21:53:50

I never understand how questions like this ever get upvoted. They are EXACTLY like the correct answer yet.. 2 years later lol

Related Questions

Sponsored Content

38 Answered Questions

34 Answered Questions

[SOLVED] How do I make a placeholder for a 'select' box?

17 Answered Questions

[SOLVED] Change the selected value of a drop-down list with jQuery

23 Answered Questions

[SOLVED] What are valid values for the id attribute in HTML?

  • 2008-09-16 09:08:52
  • Mr Shark
  • 455679 View
  • 2049 Score
  • 23 Answer
  • Tags:   html

28 Answered Questions

[SOLVED] Set select option 'selected', by value

28 Answered Questions

[SOLVED] Get selected value in dropdown list using JavaScript

14 Answered Questions

[SOLVED] How can I select an element by name with jQuery?

32 Answered Questions

[SOLVED] How can I change an element's class with JavaScript?

  • 2008-10-12 20:06:43
  • Nathan Smith
  • 2668667 View
  • 2843 Score
  • 32 Answer
  • Tags:   javascript html dom

Sponsored Content