如何使用 jQuery、JavaScript 和 HTML 动态设置下拉列表的选定选项?

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

How do I dynamically set the selected option of a drop-down list using jQuery, JavaScript and HTML?

javascriptjqueryhtml

提问by Eric Hunt

For some reason, I can't get this to work.

出于某种原因,我无法让它发挥作用。

My options list is populated dynamically using these scripts:

我的选项列表是使用这些脚本动态填充的:

function addOption(selectId, value, text, selected) {
    var html = '<option value="'+value+'">'+text+'</option>';
    if (selected == "on") {
        html = '<option value="'+value+'" selected="selected">'+text+'</option>';
    }
    $('#'+selectId).append(html);
}

function addSalespersonOption(id, name, defsales) {
    addOption('salesperson', id, name, defsales);
}

Here is the HTML:

这是 HTML:

<td class="text-r"><label for="salesperson">Salesperson:</label></td>
<td>
    <select id="salesperson">
        <option value="">(select)</option>
    </select>
</td>

So far, the output is:

到目前为止,输出是:

<option value="1266852143634" selected="selected">Eric Hunt</option>

The DOM shows this:

DOM 显示了这一点:

index              2
disabled           false
value              "1266852143634"
text               "Eric Hunt"
selected           false
defaultSelected    true

But for some reason, when the page is loaded, the dropdown does not display Eric Hunt as pre selected. Nor is anything for that matter.

但出于某种原因,当页面加载时,下拉列表不会将 Eric Hunt 显示为预选。也不是任何事情。

How can I get "selected true" instead of "defaultSelected true"?

如何获得“selected true”而不是“defaultSelected true”?



EDIT: As it turns out, the above code works perfectly, thanks to the help of decezeand rosscj2533's answers from below. The only reason it's not working for me is, I found Ruby code that was overwriting the select elements.

编辑:事实证明,由于decezerosscj2533来自下面的答案的帮助,上面的代码运行良好。它对我不起作用的唯一原因是,我发现 Ruby 代码覆盖了 select 元素。

Thanks for everyone's help on this,

感谢大家在这方面的帮助,

Cheers

干杯

回答by deceze

The defaultSelectedattribute is not settable, it's just for informational purposes:

defaultSelected属性不可设置,仅供参考:

Quote:

报价

The defaultSelected property returns the default value of the selected attribute.
This property returns true if an option is selected by default, otherwise it returns false.

defaultSelected 属性返回所选属性的默认值。
如果默认选择了一个选项,则此属性返回 true,否则返回 false。

I think you want:

我想你想要:

$('option[value=valueToSelect]', newOption).attr('selected', 'selected');

I.e. set the selectedattribute of the optionyou want to select.

即设置您要选择的selected属性option



Without trying to fix your code, here's roughly how I would do it:

在不尝试修复您的代码的情况下,这大致是我的做法:

function buildSelect(options, default) {
    // assume options = { value1 : 'Name 1', value2 : 'Name 2', ... }
    //        default = 'value1'

    var $select = $('<select></select>');
    var $option;

    for (var val in options) {
        $option = $('<option value="' + val + '">' + options[val] + '</option>');
        if (val == default) {
            $option.attr('selected', 'selected');
        }
        $select.append($option);
    }

    return $select;
}

You seem to have a lot of baggage and dependencies already and I can't tell you how to best integrate the selected option into your code without seeing more of it, but hopefully this helps.

您似乎已经有很多包袱和依赖项,我无法告诉您如何最好地将所选选项集成到您的代码中而不看到更多,但希望这会有所帮助。

回答by Tamilan

SCRIPT

脚本

 <script type="text/javascript">
    $(function(){
        $("#gender").val("Male").attr("selected","selected");
    });
 </script>

HTML

HTML

<select id="gender" selected="selected">
    <option>--Select--</option>
    <option value="1">Male</option>
    <option value="2">Female</option>
</select>

Click Here More Details

点击这里更多详情

回答by Hetal Vora

Here is another way you can change the selected option of a <select>element in javascript. You can use

这是您可以<select>在 javascript 中更改元素的选定选项的另一种方法。您可以使用

document.getElementById('salesperson').selectedIndex=1;

document.getElementById('salesperson').selectedIndex=1;

Setting it to 1 will make the second element of the dropdown selected. The select element index start from 0.

将其设置为 1 将使下拉列表的第二个元素被选中。选择元素索引从 0 开始。

Here is a sample code. Check if you can use this type of approach:

这是一个示例代码。检查您是否可以使用这种方法:

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

function changeSelected() { 
document.getElementById('salesperson').selectedIndex=1;

} 

</script>
</head>
<body>
<form name="f1">

<select id="salesperson" > 
   <option value"">james</option>
   <option value"">john</option>  
</select> 
<input type="button" value="Change Selected" onClick="changeSelected();">

</form>
</body>
</html>

回答by Daniel McGrath

Pardon my ignorance, but why are you using $('.salesperson')instead of $('#salesperson')when dealing with an ID?

请原谅我的无知,但是为什么在处理 ID 时使用$('.salesperson')而不是$('#salesperson')

回答by rosscj2533

Your code works for me. When does addSalespersonOptionget called? There may be a problem with that call.

你的代码对我有用。什么时候addSalespersonOption被调用?那个调用可能有问题。

Also some of your html is a bit off (maybe copy/paste problem?), but that didn't seem to cause any problems. Your select should look like this:

还有一些 html 有点偏离(可能是复制/粘贴问题?),但这似乎没有引起任何问题。您的选择应如下所示:

<select id="salesperson"> 
    <option value="">(select)</option> 
</select>

instead of this:

而不是这个:

<select id="salesperson" /> 
    <option value"">(select)</option> 
</select>

Edit: When does your options list get dynamically populated? Are you sure you are passing 'on'for the defSalesvalue in your call to addSalespersonOption? Try changing that code to this:

编辑:您的选项列表何时动态填充?您确定要传递调用中'on'defSalesaddSalespersonOption吗?尝试将该代码更改为:

if (selected == "on") { 
    alert('setting default selected option to ' + text);
    html = '<option value="'+value+'" selected="selected">'+text+'</option>'; 
} 

and see if the alert happens and what is says if it does happen.

并查看警报是否发生以及如果发生警报会说明什么。

Edit: Working exampleof my testing (the error:undefined is from jsbin, not my code).

编辑:我的测试的工作示例(错误:未定义来自 jsbin,而不是我的代码)。

回答by Sairam Kukadala

Here it goes.

就到这里了。

// Select by value
$('select[name="options"]').find('option[value="3"]').attr("selected",true);

// Select by text
//$('select[name="options"]').find('option:contains("Third")').attr("selected",true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<html>
<body>
<select name="options">
      <option value="1">First</option>
      <option value="2">Second</option>
      <option value="3">Third</option>
</select>
</body>
</html>

回答by SLaks

Your syntax is wrong.

你的语法是错误的。

You need to call attrwith two parameters, like this:

您需要attr使用两个参数进行调用,如下所示:

$('.salesperson', newOption).attr('defaultSelected', "selected");

Your current code assigns the value "selected"to the variable defaultSelected, then passes that value to the attrfunction, which will then return the value of the selectedattribute.

您当前的代码将值分配"selected"给变量defaultSelected,然后将该值传递给attr函数,然后函数将返回selected属性的值。