How can I set the default value for an HTML <select> element?

Viewed 3388732

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?

34 Answers

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 has 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. If XML compliance is important you should follow the full syntax.

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

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>

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>

You can use:

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

instead of,

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

both are equally correct.

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

please see below example

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

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>

This example has been tested to work with multiple <select> elements on the page, and can also work with normal text elements. It has not been tested for setting the value to more than one selection when <select multiple="true">, however you can probably modify this sample to support that.

  • Add an attribute data-selected to each <select> element and set the value(s) to the value of the option you wish to have selected.

  • Use javascript's querySelectorAll() to select all elements that have the custom attribute you just added.

In the following example, when run, the first <select> should show option with the value user as selected, and the second <select> should show the option with the value admin as selected.

document.querySelectorAll('[data-selected]').forEach(e => {
   e.value = e.dataset.selected
});
<select data-selected="user" class="form-control" name="role">
    <option value="public">
        Pubblica
    </option>
    <option value="user">
        Utenti
    </option>
    <option value="admin">
        Admin
    </option>
</select>


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

Default selected value is Option-4

  <html:select property="status" value="OPTION_4" styleClass="form-control">
            <html:option value="">Select</html:option>
            <html:option value="OPTION_1"  >Option-1</html:option>
            <html:option value="OPTION_2"  >Option-2</html:option>
            <html:option value="OPTION_3"  >Option-3</html:option>
            <html:option value="OPTION_4"  >Option-4</html:option>
            <html:option value="OPTION_5"  >Option-5</html:option>                                  
   </html:select>

You will need an "id" attribute in each option for this solution to work:

<script>
function select_option (id,value_selected) {

 var select; 
 select = document.getElementById(id);
 if (select == null) return 0;
 
 var option;
 option = select.options.namedItem(value_selected);
 if (option == null) return 0;

 option.selected = "selected";
 return true;
} 
</script>

<select name="hall" id="hall">
  <option id="1">1</option>
  <option id="2">2</option>
  <option id="3">3</option>
  <option id="4">4</option>
  <option id="5">5</option>
</select>
<script>select_option ("hall","3");</script> 

The function first tries to find the <select> with the id, then it will search for the value_selected in the <select> options and if it finds it, it will set the selected attribute returning true. False otherwise

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>

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

To set the default using PHP and JavaScript:

State: <select id="State">
<option value="" selected disabled hidden></option>
<option value="Andhra Pradesh">Andhra Pradesh</option>
<option value="Andaman and Nicobar Islands">Andaman and Nicobar Islands</option>
.
.
<option value="West Bengal">West Bengal</option>
</select>
<?php
if(isset($_GET['State'])){
    echo <<<heredoc
<script>
document.getElementById("State").querySelector('option[value="{$_GET['State']}"]').selected = true;
</script>
heredoc;
}
?>

This is simple method to make default option selected.

Can be used for multiple selects on an HTML page.

The method:

  • Find every select
  • Read the id and value of that select
  • Make the option selected

Note:

  • Every select must have ID to avoid conflict

$(document).ready(function() {
  // Loop for every select in page
  $('select').each(function(index, id) {
    // Get the value 
    var theValue = $(this).attr('value');

    // Get the ID  
    var theID = $(this).attr('id');

    // Make option selected 
    $('select#' + theID + ' option[value=' + theValue + ']').attr('selected', true);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<select id="sport" name="sport" class="autoselect" value="golf">
<option value="basket">Basket Ball</option>
<option value="tennis">Tennis</option>
<option value="golf">Golf</option>
<option value="bowling">Bowling</option>
</select>

<hr>

<select id="tools" name="tools" class="autoselect" value="saw">
<option value="hammer">Hammer</option>
<option value="drill">Drill</option>
<option value="screwdriver">Screwdriver</option>
<option value="saw">Saw</option>
<option value="wrench">Wrench</option>
</select>

I was having some troubles with it because I need some way to choose the option dynamically accordingly to the value that I have in the database. The script bellow works like a charm to me:

<?php
//pick the value of database
$selected_sexo = $query['s_sexo'];
?>

<select name="s_sexo" id="s_sexo" required>
  <option <?php if($selected_sexo == 'M'){echo("selected");}?> value="M">M</option>
  <option <?php if($selected_sexo == 'F'){echo("selected");}?> value="F">F</option>
</select>

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

none of these answer worked for me, reason is that I had an array in my database containing the previous selection and I wanted the user to see highlighted the same selections he had made the last time before changing them. I am also using React that doesn't like the selected tag.

VM71 react_devtools_backend.js:3973 Warning: Use the `defaultValue` or `value` props on <select> instead of setting `selected` on <option>

Thus I decided to manipulate the docref.options directly. Inside React you have to use a useRef hook to do this, so you will see the .current property where the actual Ref is store. You get this by adding the ref= in your html line with the tag select.

Here is the useEffect code, for those not using React just get the code out of the hook, this code is executed by React every time it renders the component.

    useEffect(() => {
            if(optionRef?.current!==undefined) { // only do something when optionRef has been assigned a doc reference by React
                [...optionRef.current.options]?.filter(option => option.value === optionTypes?.filter(type => type===option.value)[0])?.map(option=> option.selected=true) 
// because optionTypes is an array of strings, due to using multiple selection, in my case only one match is possible, thus just convert the first and only string of the resulting array to string with the [0]
// this one liner is all that you need if not using react, I only tested it in React
            }
    }) // I am making it trigger every time it renders, couldn't make it work when tracking optionRef changes or optionRef.current changes, it wouldn't trigger despite the change of optionRef. To make it work I'd probable have to change a state variable every time that optionRef changes, so I decided to just execute this code for every render

HTML part inside a return in React:

<select 
    name="optionType"
    id="idNumber"
    ref={optionRef}
    multiple={true}
    size={3}
> {/* determines the number of elements that will fit into the selection window*/}
    <option value="" disabled hidden>Choose Option</option>
    <option value="Option1">Option1</option>
</select>
Select Ticket type

disabeled are not friendly in such situations

Related