Blank HTML SELECT without blank item in dropdown list

前端 未结 8 1387
我寻月下人不归
我寻月下人不归 2020-12-23 08:37

How implement subj?

when i write:

提交评论

  • 2020-12-23 09:15

    Here is a simple way to do it using plain JavaScript. This is the vanilla equivalent of the jQuery script posted by pimvdb. You can test it here.

    <script type='text/javascript'>
      window.onload = function(){
        document.getElementById('id_here').selectedIndex = -1;
      }
    </script>
    

    .

    <select id="id_here">
      <option>aaaa</option>
      <option>bbbb</option>
    </select>
    

    Make sure the "id_here" matches in the form and in the JavaScript.

    0 讨论(0)
  • 2020-12-23 09:16

    Simply using

    <option value="" selected disabled>Please select an option...</option>
    

    will work anywhere without script and allow you to instruct the user at the same time.

    0 讨论(0)
  • 2020-12-23 09:20

    Just use disabled and/or hidden attributes:

    <option selected disabled hidden style='display: none' value=''></option>
    
    • selected makes this option the default one.
    • disabled makes this option unclickable.
    • style='display: none' makes this option not displayed in older browsers. See: Can I Use documentation for hidden attribute.
    • hidden makes this option to don't be displayed in the drop-down list.
    0 讨论(0)
  • 2020-12-23 09:26

    You can by setting selectedIndex to -1 using .prop: http://jsfiddle.net/R9auG/.

    For older jQuery versions use .attr instead of .prop: http://jsfiddle.net/R9auG/71/.

    0 讨论(0)
  • 2020-12-23 09:26

    You can't. They simply do not work that way. A drop down menu must have one of its options selected at all times.

    You could (although I don't recommend it) watch for a change event and then use JS to delete the first option if it is blank.

    0 讨论(0)
  • 提交回复
    热议问题