如何在下拉javascript中选择值?

时间:2021-08-12 20:06:14

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

9 个解决方案

#1


91  

Use the selectedIndex property:

使用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;
        }
    }
}

#2


16  

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是你的下拉香蕉的名字只是你下拉列表中的一个项目

#3


14  

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

#4


8  

The simplest possible solution if you know the value

如果你知道这个值,这是最简单的可能解

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

#5


4  

This may do it

这可能会这样做

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

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

#6


4  

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' answer got me 90% there. However, for my use case, selecting the item from the dropdown also triggered an action on the page from dropdown's onchange event. James' code as 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事件页面上的操作。詹姆斯编写的代码没有触发这个事件(至少在我正在测试的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 value is not found; this is needed for my use case.

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

#7


1  

Yes. As mentioned in the posts, value property is nonstandard and does not work with IE. You will need to use the selectedIndex property 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所言,它目前受到支持。

#8


1  

Refer this article. They have explained it in many ways using JavaScript or Jquery.

参考这篇文章。他们使用JavaScript或Jquery以多种方式对其进行了解释。

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

#9


0  

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.firstChild will actually be your first option tag. Then, by doing option.nextElementSibling you can go to the next option tag, so the next choice in your dropdownlist element. If you want to get the number of option tags you can use dropDownList.length which I used in the for loop.

它。firstChild实际上是您的第一个选项标记。然后,通过选择。您可以转到下一个选项标签,因此在下拉列表元素中选择下一个选项。如果您想获得选项标签的数量,可以使用下拉列表。我在for循环中使用的长度。

Hope this helps someone.

希望这可以帮助别人。

#1


91  

Use the selectedIndex property:

使用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;
        }
    }
}

#2


16  

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是你的下拉香蕉的名字只是你下拉列表中的一个项目

#3


14  

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

#4


8  

The simplest possible solution if you know the value

如果你知道这个值,这是最简单的可能解

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

#5


4  

This may do it

这可能会这样做

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

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

#6


4  

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' answer got me 90% there. However, for my use case, selecting the item from the dropdown also triggered an action on the page from dropdown's onchange event. James' code as 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事件页面上的操作。詹姆斯编写的代码没有触发这个事件(至少在我正在测试的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 value is not found; this is needed for my use case.

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

#7


1  

Yes. As mentioned in the posts, value property is nonstandard and does not work with IE. You will need to use the selectedIndex property 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所言,它目前受到支持。

#8


1  

Refer this article. They have explained it in many ways using JavaScript or Jquery.

参考这篇文章。他们使用JavaScript或Jquery以多种方式对其进行了解释。

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

#9


0  

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.firstChild will actually be your first option tag. Then, by doing option.nextElementSibling you can go to the next option tag, so the next choice in your dropdownlist element. If you want to get the number of option tags you can use dropDownList.length which I used in the for loop.

它。firstChild实际上是您的第一个选项标记。然后,通过选择。您可以转到下一个选项标签,因此在下拉列表元素中选择下一个选项。如果您想获得选项标签的数量,可以使用下拉列表。我在for循环中使用的长度。

Hope this helps someone.

希望这可以帮助别人。