如何为 HTML 选择设置默认值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19611557/
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 14:46:55  来源:igfitidea点击:

How to set default value for HTML select?

javascripthtml

提问by Saman

I have a HTML select like this:

我有一个像这样的 HTML 选择:

<select>
    <option>a</option>
    <option>b</option>
    <option>c</option>
</select>

and I have a variable named tempin my JavaScript:

temp我的 JavaScript 中有一个名为的变量:

var temp = "a";

Now I want to set the value of the option that is equal to temp as default value for my select.

现在我想将等于 temp 的选项的值设置为我的选择的默认值。

How can I do it?

我该怎么做?

回答by Sébastien

You first need to add values to your selectoptions and for easy targetting give the selectitself an id.

您首先需要为您的select选项添加值,并为方便定位给它select本身一个id.

Let's make option bthe default:

让我们将选项设为b默认值:

<select id="mySelect">
    <option>a</option>
    <option selected="selected">b</option>
    <option>c</option>
</select>

Now you can change the default selected value with JavaScript like this:

现在,您可以使用 JavaScript 更改默认选定值,如下所示:

<script>
var temp = "a";
var mySelect = document.getElementById('mySelect');

for(var i, j = 0; i = mySelect.options[j]; j++) {
    if(i.value == temp) {
        mySelect.selectedIndex = j;
        break;
    }
}
</script>

See it in action on codepen.

codepen上查看它的实际效果

回答by Portland Runner

Note: this is JQuery. See Sébastien answer for Javascript

注意:这是 JQuery。请参阅 Sébastien 对 Javascript 的回答

$(function() {
    var temp="a"; 
    $("#MySelect").val(temp);
});

<select name="MySelect" id="MySelect">
    <option value="a">a</option>
    <option value="b">b</option>
    <option value="c">c</option>
</select>

回答by user2923853

You should define the attributes of optionlike selected="selected"

您应该定义optionlike selected="selected"的属性

<select>
   <option selected="selected">a</option>
   <option>b</option>
   <option>c</option>
</select>

回答by Naveen Kumar Alonekar

Simplay you can place HTML selectattribute to option alike shown below

Simplay 您可以将 HTML选择属性放置到a如下所示的选项中

Define the attributes like selected="selected"

定义属性,如 selected="selected"

<select>
   <option selected="selected">a</option>
   <option>b</option>
   <option>c</option>
</select>

回答by siddharth jambukiya

you can define attribute selected="selected" in Ex a

您可以在 Ex a 中定义属性 selected="selected"

回答by Gavin

You could use...

你可以用...

<option <?= ($temp == $value) ? "SELECTED" : "" ?> >$value</opton>

Edit: I thought I was looking at PHP questions... Sorry.

编辑:我以为我在看 PHP 问题...抱歉。