使用 JavaScript 更改 Select 标记值

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

Change Select tag value using JavaScript

javascriptselectgetelementbyid

提问by edsonski

I'm trying to change a value from a select tag using JavaScript. Let's say that I have this textbox, and if that textbox is null, no changes will be done and the value of the select tag options will be as is. But if that textbox is filled, then I have to assign a different value aside from the ones in the select tag options.

我正在尝试使用 JavaScript 更改选择标记中的值。假设我有这个文本框,如果该文本框为空,则不会进行任何更改,并且选择标记选项的值将保持原样。但是,如果该文本框已填充,则除了选择标记选项中的值之外,我还必须分配一个不同的值。

Here's what I'm trying to do:

这是我想要做的:

HTML:

HTML:

<input type="text" id="txtTest" />
<select name="rdoSelect" id="rdoSelect">
  <option value="option1">Option 1</option>
  <option value="option2">Option 2</option>
</select>

JavaScript:

JavaScript:

if (document.getElementById('txtTest').value===null)
{
    document.getElementById('rdoSelect').value;
}
else
{
    document.getElementById('rdoSelect').value = "option 3";
}

I can't make it work. I've tried pointing it to an element/variable rather than to a value and it still doesn't work:

我不能让它工作。我试过将它指向一个元素/变量而不是一个值,但它仍然不起作用:

var test = document.getElementById('rdoSelect');
test.value = "option 3";

I need help, please. Thanks!

我需要帮助,请。谢谢!

回答by SMS

Try using SelectIndex method. Please refer the below code.

尝试使用 SelectIndex 方法。请参考以下代码。

I added OnChange event to input text to test this sample.

我将 OnChange 事件添加到输入文本以测试此示例。

<html>
<head>
<script language="javascript">

    function test()
    {   
        if (document.getElementById('txtTest').value=='')
        {
            document.getElementById("rdoSelect").selectedIndex = 0;
        }
        else
        {
            document.getElementById("rdoSelect").selectedIndex = 1;
        }
    }

</script>
</head>
<body>
<input type="text" id="txtTest" onchange="test();" />
<select name="rdoSelect" id="rdoSelect">
  <option value="option1">Option 1</option>
  <option value="option2">Option 2</option>
</select>
</body>
</html>

回答by hima

Is this happening on button click or onkeyup? Either way in the function you can add value to dropdownlist using this:

这是在单击按钮还是 onkeyup 时发生的?无论哪种方式在函数中,您都可以使用以下方法向下拉列表添加值:

dropdownlist.append(
    $("<option selected='selected'></option>").val(sValId).html(sVal)
);

Or you colud try this

或者你可以试试这个

var optn = document.createElement("OPTION");
optn.text = "--Select--";
optn.value = "0";
baseCurve.options.add(optn);`

回答by bobince

HTMLSelectElement doesn't let you set the valuedirectly. It's possible to have many or zero <option>s with a particular value, so it's not a straightforward 1:1 mapping.

HTMLSelectElement 不允许您value直接设置。可能有多个或零<option>具有特定值,因此它不是简单的 1:1 映射。

To select an option you can either set its selectedproperty to true, or set the selectedIndexproperty of the select to the option number.

要选择一个选项,您可以将其selected属性设置为true,或者将selectedIndex选择的属性设置为选项编号。

There is no option 3in your select—are you trying to add a new option?

option 3您的选择中没有- 您是否要添加新选项?

eg

例如

function setOrCreateSelectValue(select, value) {
    for (var i= select.options.length; i-->0;) {
        if (select.options[i].value==value) {
            select.selectedIndex= i;
            return;
        }
    }
    select.options[select.options.length]= new Option(value, value, true, true);
}

回答by zeenfaiz

    if (document.getElementById('txtTest').value===null)
    {
        document.getElementById('rdoSelect').value;
    }
    else
    {
       var val = document.getElementById('txtTest').value
       for(var i, j = 0; i = rdoSelect.options[j]; j++) {
        if(i.value == val) {
            rdoSelect.selectedIndex = j;
            break;
        }
    }

}

回答by mitjak

Take a look at this jsfiddle, it's using jquery, which is probably the most common solution. Hope it helps.

看看这个 jsfiddle,它使用的是 jquery,这可能是最常见的解决方案。希望能帮助到你。

http://jsfiddle.net/GkLsZ/

http://jsfiddle.net/GkLsZ/

$(function() {
    $('#btnChange').on('click', function() {
        var value = $.trim($('#txtTest').val());

        if (!!value) {
            $('#rdoSelect')
                .append($("<option></option>")
                .attr("value", value)
                .attr("selected", "selected")
                .text(value)); 
        }
    });
});