Javascript 如何在下拉javascript中选择一个值?

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

How to select a value in dropdown javascript?

javascript

提问by karthick

i have a drop down like this

我有一个这样的下拉菜单

<select style="width: 280px" id="Mobility" name="Mobility">
  <option selected="">Please Select</option>
  <option>K</option>
  <option>1</option>
  <option>2</option>
  <option>3</option>
  <option>4</option>
  <option>5</option>
  <option>6</option>
  <option>7</option>
  <option>8</option>
  <option>9</option>
  <option>10</option>
  <option>11</option>
  <option>12</option>
</select>

I use this line to select a value it works in Mozilla not in IE? Why its not working?

我使用这一行来选择它在 Mozilla 而非 IE 中工作的值?为什么它不工作?

var element = document.getElementById("Mobility");
element.value = "10";

回答by James Hill

Use the selectedIndexproperty:

使用selectedIndex属性

document.getElementById("Mobility").selectedIndex = 12; //Option 10

Alternate method:

替代方法:

Loop through each value:

循环遍历每个值:

//Get select object
var objSelect = document.getElementById("Mobility");

//Set selected
setSelectedValue(objSelect, "10");

function setSelectedValue(selectObj, valueToSet) {
    for (var i = 0; i < selectObj.options.length; i++) {
        if (selectObj.options[i].text== valueToSet) {
            selectObj.options[i].selected = true;
            return;
        }
    }
}

回答by Amin

easiest way is to just use this

最简单的方法是使用这个

document.getElementById("mySelect").value = "banana";

myselect is name of your dropdown banana is just one of items in your dropdown list

myselect 是下拉菜单的名称 香蕉只是下拉列表中的项目之一

回答by GregM

function setSelectedIndex(s, v) {
    for ( var i = 0; i < s.options.length; i++ ) {
        if ( s.options[i].value == v ) {
            s.options[i].selected = true;
            return;
        }
    }
}

Where s is the dropdown and v is the value

其中 s 是下拉列表,v 是值

回答by Gabor

The simplest possible solution if you know the value

如果您知道价值,最简单的可能解决方案

document.querySelector('option[value=" + value +"]').selected = true

回答by Doug R.

I realize that this is an old question, but I'll post the solution for my use case, in case others run into the same situation I did when implementing James Hill's answer (above).

我意识到这是一个老问题,但我会发布我的用例的解决方案,以防其他人遇到与我在实施James Hill 的回答(上面)时遇到的情况相同的情况。

I found this question while trying to solve the same issue. James' answergot me 90% there. However, for my use case, selecting the item from the dropdown also triggered an action on the page from dropdown's onchangeevent. James' codeas written did not trigger this event (at least in Firefox, which I was testing in). As a result, I made the following minor change:

我在尝试解决同一问题时发现了这个问题。 詹姆斯的回答让我达到了 90%。但是,对于我的用例,从下拉列表中选择项目也会从下拉onchange事件的页面上触发一个操作。James编写的代码没有触发这个事件(至少在我测试的 Firefox 中)。因此,我做了以下小改动:

function setSelectedValue(object, value) {
    for (var i = 0; i < object.options.length; i++) {
        if (object.options[i].text === value) {
            object.options[i].selected = true;
            object.onchange();
            return;
        }
    }

    // Throw exception if option `value` not found.
    var tag = object.nodeName;
    var str = "Option '" + value + "' not found";

    if (object.id != '') {
        str = str + " in //" + object.nodeName.toLowerCase()
              + "[@id='" + object.id + "']."
    }

    else if (object.name != '') {
        str = str + " in //" + object.nodeName.toLowerCase()
              + "[@name='" + object.name + "']."
    }

    else {
        str += "."
    }

    throw str;
}

Note the object.onchange()call, which I added to the original solution. This calls the handler to make certain that the action on the page occurs.

请注意object.onchange()我添加到原始解决方案中的调用。这将调用处理程序以确保页面上的操作发生。

Edit

编辑

Added code to throw an exception if option valueis not found; this is needed for my use case.

添加了value在未找到选项时抛出异常的代码;这是我的用例所需要的。

回答by Dylan Valade

This may do it

这可以做到

document.forms['someform'].elements['someelement'].value

document.forms['someform'].elements['someelement'].value

回答by Dylan Valade

Using Javascript:

使用 JavaScript:

document.getElementById('drpSelectSourceLibrary').value = 'Seven';

Using Jquery:

使用jQuery:

$('select').prop('selectedIndex', 3); // This will select the 4th option from the dropdown list

回答by Alain Paquette

Instead of doing

而不是做

function setSelectedIndex(s, v) {
    for ( var i = 0; i < s.options.length; i++ ) {
        if ( s.options[i].value == v ) {
            s.options[i].selected = true;
            return;
        }
    }
}

I solved this problem by doing this

我通过这样做解决了这个问题

function setSelectedValue(dropDownList, valueToSet) {
    var option = dropDownList.firstChild;
    for (var i = 0; i < dropDownList.length; i++) {
        if (option.text.trim().toLowerCase() == valueToSet.trim().toLowerCase()) {
            option.selected = true;
            return;
        }
        option = option.nextElementSibling;
    }
}

If you work with strings, you should use the .trim()method, sometimes blank spaces can cause trouble and they are hard to detect in javascript debugging sessions.

如果您使用字符串,则应该使用该.trim()方法,有时空格会导致麻烦,并且在 javascript 调试会话中很难检测到它们。

dropDownList.firstChildwill actually be your first optiontag. Then, by doing option.nextElementSiblingyou can go to the next optiontag, so the next choice in your dropdownlist element. If you want to get the number of optiontags you can use dropDownList.lengthwhich I used in the for loop.

dropDownList.firstChild实际上将是您的第一个option标签。然后,通过这样做,option.nextElementSibling您可以转到下一个option标签,因此您的下拉列表元素中的下一个选择。如果你想获得我在 for 循环中option使用的标签数量,你可以使用dropDownList.length它。

Hope this helps someone.

希望这可以帮助某人。

回答by James Jithin

Yes. As mentioned in the posts, valueproperty is nonstandard and does not work with IE. You will need to use the selectedIndexproperty to achieve this. You can refer to the w3schools DOM reference to see the properties of HTML elements. The following link will give you the list of properties you can work with on the select element.

是的。正如帖子中提到的,value属性是非标准的,不适用于 IE。您将需要使用该selectedIndex属性来实现此目的。您可以参考 w3schools DOM 参考来查看 HTML 元素的属性。以下链接将为您提供可以在 select 元素上使用的属性列表。

http://www.w3schools.com/jsref/dom_obj_select.asp

http://www.w3schools.com/jsref/dom_obj_select.asp

Update

更新

This was not supported during 2011 on IE. As commented by finnTheHuman, it is supported at present.

这在 2011 年期间在 IE 上不受支持。正如 finnTheHuman 评论的那样,目前支持它。

回答by Kunal Mukherjee

Using some ES6:

使用一些 ES6:

Get the options first, filter the value based on the option and set the selected attribute to true.

首先获取选项,根据选项过滤值并将selected属性设置为true。

window.onload = () => {

  Array.from(document.querySelector(`#Mobility`).options)
    .filter(x => x.value === "12")[0]
    .setAttribute('selected', true);

};
<select style="width: 280px" id="Mobility" name="Mobility">
  <option selected disabled>Please Select</option>
  <option>K</option>
  <option>1</option>
  <option>2</option>
  <option>3</option>
  <option>4</option>
  <option>5</option>
  <option>6</option>
  <option>7</option>
  <option>8</option>
  <option>9</option>
  <option>10</option>
  <option>11</option>
  <option>12</option>
</select>