element"/> element">
Home >Web Front-end >Front-end Q&A >How to make the select tag expand by default in javascript
In HTML, the
Implementation method:
1. Use the autofocus attribute of HTML5
The easiest way is to use the autofocus attribute of HTML5. This attribute can automatically set focus on the specified input box, button, drop-down list and other elements after the page is loaded. To make a
<select autofocus> <option value="1">Option 1</option> <option value="2">Option 2</option> <option value="3">Option 3</option> </select>
2. Using JavaScript code
When we need to expand the
<select id="mySelect"> <option value="1">Option 1</option> <option value="2">Option 2</option> <option value="3">Option 3</option> </select> <script> document.getElementById('mySelect').size = document.getElementById('mySelect').length; </script>
The above code automatically expands the drop-down list by setting its size (size) to its number of options (length). Of course, you can also use other methods to achieve the same effect, such as setting the options attribute, or using CSS styles, etc.
3. Expand
Sometimes we need to expand
<select id="mySelect"> <option value="1">Option 1</option> <option value="2">Option 2</option> <option value="3">Option 3</option> </select> <script> document.getElementById('mySelect').addEventListener('click', function() { this.size = this.length; }); </script>
The above code listens to the click event of
Note:
Although using JavaScript code can easily realize the expansion of