如何设置 HTML

发布于 2024-09-15 04:12:47 字数 518 浏览 4 评论 0原文

我认为在下面的

<select name="hall" id="hall" value="3">
  <option>1</option>
  <option>2</option>
  <option>3</option>
  <option>4</option>
  <option>5</option>
</select>

然而,这并没有像我预期的那样起作用。如何设置默认选择哪个 元素?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

会发光的星星闪亮亮i 2024-09-22 04:12:48

标签的 value 属性丢失,因此它没有按您想要的选择显示。默认情况下,如果在标签上设置了 value 属性,则第一个选项显示在下拉页面加载上......我用这种方式解决了我的问题

value attribute of tag is missing, so it doesn't show as u desired selected. By default first option show on dropdown page load, if value attribute is set on tag.... I got solved my problem this way

执手闯天涯 2024-09-22 04:12:48

我只需将第一个选择选项值设置为默认值,然后使用 HTML5 的新“隐藏”功能将该值隐藏在下拉列表中。像这样:

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

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>
心是晴朗的。 2024-09-22 04:12:48

此示例已经过测试,可以与页面上的多个 时将值设置为多个选择的情况,但是您可以修改此示例以支持这一点。

  • 向每个

  • 使用 JavaScript 的 querySelectorAll() 选择具有您刚刚添加的自定义属性的所有元素。

在以下示例中,运行时,第一个 应显示选项code> 应显示所选值为 admin 的选项。

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>

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>

茶花眉 2024-09-22 04:12:48

我自己用的

<select selected=''>
    <option value=''></option>
    <option value='1'>ccc</option>
    <option value='2'>xxx</option>
    <option value='3'>zzz</option>
    <option value='4'>aaa</option>
    <option value='5'>qqq</option>
    <option value='6'>wwww</option>
</select>

I myself use it

<select selected=''>
    <option value=''></option>
    <option value='1'>ccc</option>
    <option value='2'>xxx</option>
    <option value='3'>zzz</option>
    <option value='4'>aaa</option>
    <option value='5'>qqq</option>
    <option value='6'>wwww</option>
</select>
情话难免假 2024-09-22 04:12:48

此代码使用 PHP 设置 HTML select 元素的默认值。

<select name="hall" id="hall">
<?php
    $default = 3;
    $nr = 1;
    while($nr < 10){
        if($nr == $default){
            echo "<option selected=\"selected\">". $nr ."</option>";
        }
        else{
            echo "<option>". $nr ."</option>";
        }
        $nr++;
    }
?>
</select>

This code sets the default value for the HTML select element with PHP.

<select name="hall" id="hall">
<?php
    $default = 3;
    $nr = 1;
    while($nr < 10){
        if($nr == $default){
            echo "<option selected=\"selected\">". $nr ."</option>";
        }
        else{
            echo "<option>". $nr ."</option>";
        }
        $nr++;
    }
?>
</select>
触ぅ动初心 2024-09-22 04:12:48

您可以使用:

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

代替,

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

两者同样正确。

You can use:

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

instead of,

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

both are equally correct.

泼猴你往哪里跑 2024-09-22 04:12:48

设置 selected="selected" 其中选项值为 3

请参见下面的示例

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

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

please see below example

<option selected="selected" value="3" >3</option>
伊面 2024-09-22 04:12:48

您只需将属性“selected”放在特定选项上,而不是直接选择元素。

这是具有不同值的相同和多个工作示例的片段。

   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>

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>

闻呓 2024-09-22 04:12:48

默认选择值为 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>

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>
抱猫软卧 2024-09-22 04:12:48

为了使该解决方案发挥作用,每个选项中都需要一个“id”属性:

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

该函数首先尝试查找<select>与 id,然后它将在 select> 中搜索 value_selected options,如果找到它,它将设置 selected 属性返回 true。否则为假

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

若水微香 2024-09-22 04:12:48

我使用这个 php 函数来生成选项,并将其插入到我的 HTML 中

<?php
# code to output a set of options for a numeric drop down list
# parameters: (start, end, step, format, default)
function numericoptions($start, $end, $step, $formatstring, $default)
{
  $retstring = "";
  for($i = $start; $i <= $end; $i = $i + $step)
  {
    $retstring = $retstring . '<OPTION ';
    $retstring = $retstring . 'value="' . sprintf($formatstring,$i) . '"';
    if($default == $i)
    {
      $retstring = $retstring . ' selected="selected"';
    }
    $retstring = $retstring . '>' . sprintf($formatstring,$i) . '</OPTION> ';
  }

return $retstring;
}
?>

,然后在我的网页代码中使用它,如下所示;

<select id="endmin" name="endmin">
  <?php echo numericoptions(0,55,5,'%02d',$endmin); ?>
</select>

如果 $endmin 是在每次加载页面时从 _POST 变量创建的(并且此代码位于发布的表单内),则默认情况下会选择先前选择的值。

I used this php function to generate the options, and insert it into my HTML

<?php
# code to output a set of options for a numeric drop down list
# parameters: (start, end, step, format, default)
function numericoptions($start, $end, $step, $formatstring, $default)
{
  $retstring = "";
  for($i = $start; $i <= $end; $i = $i + $step)
  {
    $retstring = $retstring . '<OPTION ';
    $retstring = $retstring . 'value="' . sprintf($formatstring,$i) . '"';
    if($default == $i)
    {
      $retstring = $retstring . ' selected="selected"';
    }
    $retstring = $retstring . '>' . sprintf($formatstring,$i) . '</OPTION> ';
  }

return $retstring;
}
?>

And then in my webpage code I use it as below;

<select id="endmin" name="endmin">
  <?php echo numericoptions(0,55,5,'%02d',$endmin); ?>
</select>

If $endmin is created from a _POST variable every time the page is loaded (and this code is inside a form which posts) then the previously selected value is selected by default.

王权女流氓 2024-09-22 04:12:48

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

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>
一杆小烟枪 2024-09-22 04:12:48

设置默认选项

我使用 Angular,并通过HTML 模板

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

脚本:

sselectedVal:any="test1";

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";
老子叫无熙 2024-09-22 04:12:48

你可以这样尝试

  <select name="hall" id="hall">
      <option>1</option>
      <option>2</option>
      <option selected="selected">3</option>
      <option>4</option>
      <option>5</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>
吃兔兔 2024-09-22 04:12:48

要使用 PHP 和 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;
}
?>

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;
}
?>
淡墨 2024-09-22 04:12:48

这是选择默认选项的简单方法。

可用于 HTML 页面上的多个选择。

方法:

  • 查找每个select
  • 读取该select的id和值
  • 使该选项被选中

注意:

  • 每个select必须有ID以避免冲突
$(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>

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>

匿名的好友 2024-09-22 04:12:48

我遇到了一些麻烦,因为我需要某种方法来根据数据库中的值动态选择选项。下面的脚本对我来说就像一个魅力:

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

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>
假装爱人 2024-09-22 04:12:47

selected="selected" 设置为您想要设为默认的选项。

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

Set selected="selected" for the option you want to be the default.

<option selected="selected">
3
</option>
本宫微胖 2024-09-22 04:12:47

如果您想要将默认文本作为一种占位符/提示,但不被视为有效值(例如“在此处完成”、“选择您的国家”等),您可以执行以下操作:

<select>
  <option value="" selected disabled 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>

In case you want to have a default text as a sort of placeholder/hint but not considered a valid value (something like "complete here", "select your nation" ecc.) you can do something like this:

<select>
  <option value="" selected disabled 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>

神经暖 2024-09-22 04:12:47

完整示例:

<select name="hall" id="hall"> 
  <option>1</option> 
  <option>2</option> 
  <option selected>3</option> 
  <option>4</option> 
  <option>5</option> 
</select> 

Complete example:

<select name="hall" id="hall"> 
  <option>1</option> 
  <option>2</option> 
  <option selected>3</option> 
  <option>4</option> 
  <option>5</option> 
</select> 

血之狂魔 2024-09-22 04:12:47

我遇到了这个问题,但被接受和高度评价的答案对我不起作用。事实证明,如果您使用的是 React,那么设置 selected 不起作用。

相反,您必须直接在

<select value="B">
  <option value="A">Apple</option>
  <option value="B">Banana</option>
  <option value="C">Cranberry</option>
</select>

阅读更多有关原因的信息 React 页面上

I came across this question, but the accepted and highly upvoted answer didn't work for me. It turns out that if you are using React, then setting selected doesn't work.

Instead you have to set a value in the <select> tag directly as shown below:

<select value="B">
  <option value="A">Apple</option>
  <option value="B">Banana</option>
  <option value="C">Cranberry</option>
</select>

Read more about why here on the React page.

缱绻入梦 2024-09-22 04:12:47

您可以这样做:

<select name="hall" id="hall">
    <option> 1 </option>
    <option> 2 </option>
    <option selected> 3 </option>
    <option> 4 </option>
    <option> 5 </option>
</select> 

在选项标签内提供“selected”关键字,您希望默认情况下将其显示在下拉列表中。

或者您也可以为选项标签提供属性,即

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

You can do it like this:

<select name="hall" id="hall">
    <option> 1 </option>
    <option> 2 </option>
    <option selected> 3 </option>
    <option> 4 </option>
    <option> 5 </option>
</select> 

Provide "selected" keyword inside the option tag, which you want to appear by default in your drop down list.

Or you can also provide attribute to the option tag i.e.

<option selected="selected">3</option>
无戏配角 2024-09-22 04:12:47

如果你想使用表单中的值并保持动态,请尝试使用 php

<form action="../<SamePage>/" method="post">


<?php
    $selected = $_POST['select'];
?>

<select name="select" size="1">

  <option <?php if($selected == '1'){echo("selected");}?>>1</option>
  <option <?php if($selected == '2'){echo("selected");}?>>2</option>

</select>
</form>

if you want to use the values from a Form and keep it dynamic try this with php

<form action="../<SamePage>/" method="post">


<?php
    $selected = $_POST['select'];
?>

<select name="select" size="1">

  <option <?php if($selected == '1'){echo("selected");}?>>1</option>
  <option <?php if($selected == '2'){echo("selected");}?>>2</option>

</select>
</form>
七色彩虹 2024-09-22 04:12:47

我认为最好的方法:

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

为什么不禁用?

当您将禁用属性与 一起使用时,值不会重置到原始占位符。相反,浏览器选择第一个未禁用的选项,这可能会导致用户错误。

默认空值

每个生产表单都有验证,那么空值应该不是问题。这样我们可能会有空的不需要的选择。

XHTML 语法属性

selected="selected" 语法是与 XHTML 和 HTML 5 兼容的唯一方法。这是正确的 XML 语法,一些编辑器可能对此感到高兴。它更加向后兼容。如果 XML 合规性很重要,您应该遵循完整的语法。

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.

樱娆 2024-09-22 04:12:47

我更喜欢这样:

<select>
   <option selected 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>

选择选项后“选择此处”就会消失。

I prefer this:

<select>
   <option selected 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>

'Choose here' disappears after an option has been selected.

梦一生花开无言 2024-09-22 04:12:47

nobita 答案的改进。您还可以通过隐藏元素“在此处选择”来改进下拉列表的视觉视图。

<select>
  <option selected disabled 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>

An improvement for nobita's answer. Also you can improve the visual view of the drop down list, by hiding the element 'Choose here'.

<select>
  <option selected disabled 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>

诗笺 2024-09-22 04:12:47

另一个例子;使用 JavaScript 设置选定的选项。

(您可以使用此示例将值数组循环到下拉组件中)

<select id="yourDropDownElementId"><select/>
// Get the select element
var select = document.getElementById("yourDropDownElementId");
// Create a new option element
var el = document.createElement("option");
// Add our value to the option
el.textContent = "Example Value";
el.value = "Example Value";
// Set the option to selected
el.selected = true;
// Add the new option element to the select element
select.appendChild(el);

Another example; using JavaScript to set a selected option.

(You could use this example to for loop an array of values into a drop down component)

<select id="yourDropDownElementId"><select/>
// Get the select element
var select = document.getElementById("yourDropDownElementId");
// Create a new option element
var el = document.createElement("option");
// Add our value to the option
el.textContent = "Example Value";
el.value = "Example Value";
// Set the option to selected
el.selected = true;
// Add the new option element to the select element
select.appendChild(el);
肩上的翅膀 2024-09-22 04:12:47

selected 属性是一个布尔属性。

如果存在,它指定在页面加载时应预先选择一个选项。

预先选择的选项将首先显示在下拉列表中。

<select>
  <option value="volvo">Volvo</option>
 <option value="saab">Saab</option>
 <option value="vw">VW</option>
 <option value="audi" selected>Audi</option> 
</select> 

The selected attribute is a boolean attribute.

When present, it specifies that an option should be pre-selected when the page loads.

The pre-selected option will be displayed first in the drop-down list.

<select>
  <option value="volvo">Volvo</option>
 <option value="saab">Saab</option>
 <option value="vw">VW</option>
 <option value="audi" selected>Audi</option> 
</select> 
陪你到最终 2024-09-22 04:12:47

如果您使用 React,则可以在 select 标记中使用 defaultValue 作为属性,而不是使用 value

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

眼藏柔 2024-09-22 04:12:47

如果您使用角度为 1 的 select,则需要使用 ng-init,否则,将不会选择第二个选项,因为 ng-model 会覆盖默认选定值

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

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>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文