How to specify that an option should be pre-selected when the page loads in HTML5?
Last Updated :
17 Mar, 2021
The <option> tag defines an option in a select list. The <option> tag is generally used with the value attribute to specify which value should be sent to the server for further processing. When a drop-down list is created using the <select> element, the first option or the first choice defined by the <option> tag is seen as the selected choice.
Example 1: The following example demonstrates that the first option will be pre-selected.
HTML
<!DOCTYPE html>
< html >
< head >
< style >
#container {
margin: 0 auto;
height: 300px;
width: 650px;
border: 5px solid black;
background-color: rgb(104, 241, 104);
opacity: 0.5;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.courses {
height: 60px;
width: 130px;
border: 2px solid black;
font-family: cursive;
}
</ style >
</ head >
< body >
< div id = "container" >
< h1 id = "heading1" >
Welcome to GeeksforGeeks
</ h1 >
< select class = "courses" >
< option value = "tag" >Choose Course</ option >
< option value = "Option A" >Python</ option >
< option value = "Option B" >DSA</ option >
< option value = "Option C" >C++</ option >
< option value = "Option C" >Java</ option >
</ select >
</ div >
</ body >
</ html >
|
Output: The first option “Choose Course” is pre-selected by default. But this is just not limited, we can also specify that any other option should be pre-selected when the page loads in HTML5. This can be done using the “selected” attribute. This is demonstrated in the following example.
pre-selected
Example 2: The following example demonstrates pre-selecting some other option using the selected attribute.
HTML
<!DOCTYPE html>
< html >
< head >
< title >Page Title</ title >
< style >
#container {
margin: 0 auto;
height: 300px;
width: 650px;
border: 5px solid black;
background-color: rgb(104, 241, 104);
opacity: 0.5;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.courses {
height: 60px;
width: 130px;
border: 2px solid black;
font-family: cursive;
}
</ style >
</ head >
< body >
< div id = "container" >
< h1 id = "heading1" >
Welcome to GeeksforGeeks
</ h1 >
< select class = "courses" >
< option value = "tag" >Choose Course</ option >
< option value = "Option A" >Python</ option >
< option value = "Option B" selected>DSA</ option >
< option value = "Option C" >C++</ option >
< option value = "Option C" >Java</ option >
</ select >
</ div >
</ body >
</ html >
|
Output: The third option “DSA” is pre-selected. This is due to the use of the “selected” attribute that has been specified in the option tag of “DSA”. We can pre-select any option by just specifying the selected attribute in its respective option tag.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...