Javascript 如何设置 SELECT Tag 的默认选项以及如何获取所选选项的索引?

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

How to set the default option for SELECT Tag and how to get the Index of the selected option?

javascripthtmlindexinghtml-select

提问by TopDeveloper

I would like to have a code in HTML and JavaScript that process SELECT and OPTION Elements

我想要一个处理 SELECT 和 OPTION 元素的 HTML 和 JavaScript 代码

<select>
    <option>
    </option>
    <option>
    </option>
</select>

How I can get the Index of the selected option and then get the value of this index?

如何获取所选选项的索引,然后获取该索引的值?

How can I make 2010 as the default option visual for users in the select tag existing in the form in a web page?

如何使 2010 成为网页表单中存在的选择标记中的用户的默认选项可视化?

My code looks like that :

我的代码看起来像这样:

<select id="SelectYear" name="SelectYear" size="1">  
    <script type="text/javascript">
        var startyear = "1950";
        var endyear   = "2020";
        for(var k=startyear; k<=endyear; k++ ) document.write("<option value="+k+">"+k+"</option>");
    </script>   
</select>

I tried many expressions to get that index even I know it may give a different thing like:

我尝试了许多表达式来获取该索引,即使我知道它可能会给出不同的结果,例如:

var vIndex = document.getElementById('SelectYear').selectedIndex;    
var vIndex = document.getElementById('SelectYear').selectedIndex.value;    
var vIndex = document.getElementById('SelectYear').selectedIndex.text;  
var vIndex = document.getElementById('SelectYear').options[document.getElementById('SelectYear').selectedIndex];  
var vIndex = document.getElementById('SelectYear').options[document.getElementById('SelectYear').selectedIndex].value;  
var vIndex = document.getElementById('SelectYear').options[document.getElementById('SelectYear').selectedIndex].text;

My workaround solution is to put the index static like:

我的解决方法是将索引设为静态,例如:

document.getElementById('SelectYear').selectedIndex = 60 ;

But if I do not know the exact index or the index is changed according to the changes happended in the SELECT elements due to database update or manual edit?

但是,如果我不知道确切的索引,或者由于数据库更新或手动编辑而根据 SELECT 元素中发生的更改更改了索引?

采纳答案by ajreal

<select id="SelectYear" name="SelectYear" size="1">
<script type="text/javascript">
var startyear = "1950";
var endyear   = "2020";
for(var k=startyear; k<=endyear; k++ ) 
{
  var selected = (k==2010) ? 'selected' : '';
  document.write("<option value='"+k+"'"+selected+">"+k+"</option>");
}
</script>
</select>

回答by ?ime Vidas

To set the default option based on the index, try this:

要根据索引设置默认选项,请尝试以下操作:

select_element.options[the_index].defaultSelected = true;

(You may also have to set this property to false to the previous default option.)

(您可能还必须将此属性设置为 false 为先前的默认选项。)

Source: DOM 2 HTML spec: http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-37770574

来源:DOM 2 HTML 规范:http: //www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-37770574

回答by RoToRa

selectedIndexgives you the index of the option, thus a number between 0 and the total number of options. It's neither a object nor the id of the option.

selectedIndex为您提供选项的索引,因此是一个介于 0 和选项总数之间的数字。它既不是对象也不是选项的 id。

var vSelect = document.getElementById('SelectYear')
var vIndex = vSelect.selectedIndex;
var vOption = vSelect.options[vIndex];

var vValue = vOption.value;


EDIT:

编辑:

I think I'll just babble a bit about your code, because you seem to be doing several things wrong here. This may not be related to your problem, but maybe you are willing to learn something.

我想我只会唠叨一下你的代码,因为你似乎在这里做错了几件事。这可能与您的问题无关,但也许您愿意学习一些东西。

1) Having a scriptelement inside a selectelement is invalid.

1) 在script元素中包含select元素是无效的。

2) It seems that you are using the JavaScript-Loop to basically generate something that should be static. I would be much better to simply hard code the list of options in the HTML, or even better and if you want less work, generate it server-side.

2)您似乎正在使用 JavaScript-Loop 来基本上生成一些应该是静态的东西。我会更好地简单地对 HTML 中的选项列表进行硬编码,或者甚至更好,如果您想要更少的工作,请在服务器端生成它。

3) You are speaking of the "default option", so you should also be doing that while generating the list, so either modify you JavaScript the way ajreal suggests, or, again better, directly give the option the selectedattribute in your HTML, which is also possibe (again) server-side.

3)您说的是“默认选项”,因此您在生成列表时也应该这样做,因此要么按照ajreal建议的方式修改您的JavaScript,要么更好,直接selected在您的HTML中为该选项提供属性也可能(再次)服务器端。

回答by Tom

using jQuery would make this a fairly simple process. Below assumes the select box has an id of SelectYear.

使用 jQuery 将使这成为一个相当简单的过程。下面假设选择框的 ID 为 SelectYear。

$('#SelectYear :selected').text(); //the display value
$('#SelectYear :selected').val(); // the actual value

回答by Adnan

document.getElementById("country").value = "your index";

回答by ABB

var dropDown = document.getElementById('myDropDown');
for(var i = 0; i < dropDown.options.length; i++) {
    if(dropDown.options[i].text == 'value you want to set in drop down') {
     dropDown.selectedIndex = i; 
     break;
 }

回答by CodeToLife

A chunk of working code . It will show orderDetails.typeyou want to see as default and the list of options.

一大块工作代码。它将显示orderDetails.type您希望作为默认值查看的类型和选项列表。

var selectOrderType = $("<select></select>").attr("id", "edit-orderTypes").attr("name", "orderType").attr('class', 'form-control');
var orderTypes = ['Samad', 'Said', 'Koksulton', 'Man'];
$.each(orderTypes, function (indexPrm, valPrm) {
    let flagLcl = false;
    if (orderDetails.type == valPrm) {
        flagLcl= true;
    }
    let anOptionLcl = new Option(valPrm, valPrm, flagLcl, flagLcl);
    selectOrderType.append(anOptionLcl);
});