Html 如何使用css在没有为“选择”选择任何内容时设置默认提示

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15984430/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 07:30:26  来源:igfitidea点击:

how to set a default prompt when nothing selected for "select" using css

htmlcss

提问by Norks

Is it possible to set a default prompt when nothing is selected for select box using css? or is there an elegant way to deal with this other than

当使用 css 没有为选择框选择任何内容时,是否可以设置默认提示?或者有没有其他优雅的方法来处理这个问题

 <option>Select Here</option>?

回答by Zachary Kniebel

Try this:

尝试这个:

<select>
    <option value="" disabled>Select one--</option>
    <option value="someVal1">Option 1</option>
    <option value="someVal2">Option 2</option>
    <option value="someVal3">Option 3</option>
    <option value="someVal4">Option 4</option>
</select>

回答by Mauricio Gracia Gutierrez

The accepted answer did not work for me as expected.

接受的答案对我没有预期的效果。

If you need the "Select one option" to be selected by default this worked for me

如果您需要默认选择“选择一个选项”,这对我有用

<select id="selected_option" name="selected_option">
     <option value="default" selected="selected">Select one option </option>
     <option value="someVal1">Option 1</option>
     <option value="someVal2">Option 2</option>
     <option value="someVal3">Option 3</option>
     <option value="someVal4">Option 4</option>
</select>

Is also important that the selecthas idand nameso when you submit the form the value will be part of the POST or GET

选择具有idname也很重要,因此当您提交表单时,该值将成为 POST 或 GET 的一部分

回答by S1lllver

                        <select>
                            <option style="display:none">Empty</option>
                            <option>button1</option>
                            <option>button2</option>
                        </select>

回答by worrawut

This is how I use for setup the default prompt but it will not set a default value. It use a HTML5 validation required. It may be a little bit shift from the question but I hope it could help as alternative.

这就是我用于设置默认提示的方式,但它不会设置默认值。它使用 HTML5 验证required。这可能与问题有所不同,但我希望它可以作为替代方案有所帮助。

<select id="car" name="car[brand]" required>
  <option disabled selected>Select Car Brand</option>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>

回答by SpadgeAki

Try using option with unset value

尝试使用未设置值的选项

<select>    
    <option value>Select something</option>
    <option value="1">Foo</option>
    <option value="2">Bar</option>
</select>