如何使用 jquery 设置选择下拉列表的“选定选项”

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

How to set the 'selected option' of a select dropdown list with jquery

jqueryhtmlselectedhtml-select

提问by Smudger

I have the following jquery function:

我有以下 jquery 函数:

$.post('GetSalesRepfromCustomer', {
    data: selectedObj.value
}, function (result) {
    alert(result[0]);
    $('select[name^="salesrep"]').val(result[0]);
});

result[0]is a value that I want to set as the selecteditem in my select box. result[0]equals Bruce jones.

result[0]是我想设置为selected选择框中项目的值。 result[0]等于Bruce jones.

the select box is populated by a database query but one of the rendered html is:

选择框由数据库查询填充,但呈现的 html 之一是:

<select id="salesrep" data-theme="a" data-mini="true" name="salesrep">
<option value=""> </option>
<option value="john smith">john smith</option>
<option value="Bruce Jones">Bruce Jones</option>
<option value="Adam Calitz">Adam Calitz</option>
<option>108</option>
</select>

$('select[name^="salesrep"]').val(result[0]);doesn't populate the select box selected option. I have also tried $("#salesrep").val(result[0]);without any luck.

$('select[name^="salesrep"]').val(result[0]);不填充选择框选定的选项。我也试过$("#salesrep").val(result[0]);没有任何运气。

Any help appreciated.

任何帮助表示赞赏。

so what I want is the selected / highlighted option in the salesrep dropdown list to be Bruce Jones.

所以我想要的是在销售代表下拉列表中选择/突出显示的选项是布鲁斯琼斯。

HTML to be:

HTML 为:

<select id="salesrep" data-theme="a" data-mini="true" name="salesrep">
<option value=""> </option>
<option value="john smith">john smith</option>
<option value="Bruce Jones" selected >Bruce Jones</option>
<option value="Adam Calitz">Adam Calitz</option>
<option>108</option>
</select>

Thanks again,

再次感谢,

Entire Script

整个脚本

<script type="text/javascript"> 
    $(document).ready(function () {

           $("#customer").autocomplete( 
     { 
     source: "get_customers", 
     messages: 
     { 
     noResults: '', 
     results: function() {} 
     }, 
     select: function( event, ui ) 
     { 
      var selectedObj = ui.item;        

     $.post('GetSalesRepfromCustomer', {data:selectedObj.value},function(result) { 
      alert(result[0]);
       var selnametest="Bruce Koller";
    $("#salesrep").val(selnametest);
     }); 

     } 
     });
         });


</script>

Rendered HTML is:

呈现的 HTML 是:

<select id="salesrep" data-theme="a" data-mini="true" name="salesrep">
<option value=""> </option>
<option value="RyanLubuschagne">Ryan Lubuschagne</option>
<option value="Bruce Jones">Bruce Jones</option>
<option value="Adam Calitz">Adam Calitz</option>
</select>

回答by Jb Drucker

Try this :

尝试这个 :

$('select[name^="salesrep"] option[value="Bruce Jones"]').attr("selected","selected");

Just replace option[value="Bruce Jones"]by option[value=result[0]]

只需替换option[value="Bruce Jones"]option[value=result[0]]

And before selecting a new option, you might want to "unselect" the previous :

在选择新选项之前,您可能希望“取消选择”前一个:

$('select[name^="salesrep"] option:selected').attr("selected",null);

You may want to read this too : jQuery get specific option tag text

您可能也想阅读:jQuery get specific option tag text

Edit:Using jQuery Mobile, this link may provide a good solution : jquery mobile - set select/option values

编辑:使用 jQuery Mobile,此链接可能提供了一个很好的解决方案:jquery mobile - set select/option values

回答by Zaheer Ahmed

Set the value it will set it as selected option for dropdown:

设置值,它将设置为下拉列表的选定选项:

$("#salesrep").val("Bruce Jones");

Here is working Demo

这是工作演示

If it still not working:

如果还是不行:

  1. Please check JavaScript errors on console.
  2. Make sure you included jquery files
  3. your network is not blocking jquery file if using externally.
  4. Check your view source some time exact copy of element stop jquery to work correctly
  1. 请检查控制台上的 JavaScript 错误。
  2. 确保包含 jquery 文件
  3. 如果在外部使用,您的网络不会阻止 jquery 文件。
  4. 一段时间检查您的视图源元素停止 jquery 的精确副本以正常工作

回答by Jake Zieve

One thing I don't think anyone has mentioned, and a stupid mistake I've made in the past (especially when dynamically populating selects). jQuery's .val() won't work for a select input if there isn't an option with a value that matches the value supplied.

我认为没有人提到过的一件事,以及我过去犯过的一个愚蠢的错误(尤其是在动态填充选择时)。如果没有与提供的值匹配的值的选项,jQuery 的 .val() 将不适用于选择输入。

Here's a fiddle explaining -> http://jsfiddle.net/go164zmt/

这是一个小提琴解释 - > http://jsfiddle.net/go164zmt/

<select id="example">
    <option value="0">Test0</option>
    <option value="1">Test1</option>
</select>

$("#example").val("0");
alert($("#example").val());
$("#example").val("1");
alert($("#example").val());

//doesn't exist
$("#example").val("2");
//and thus returns null
alert($("#example").val());

回答by Oscar Fuquen

You have to replace YourID and value="3" for your current ones.

您必须将 YourID 和 value="3" 替换为当前的。

$(document).ready(function() {
  $('#YourID option[value="3"]').attr("selected", "selected");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<select id="YourID">
  <option value="1">A</option>
  <option value="2">B</option>
  <option value="3">C</option>
  <option value="4">D</option>
</select>

and value="3" for your current ones.

和 value="3" 为您当前的。

$('#YourID option[value="3"]').attr("selected", "selected");

<select id="YourID" >
<option value="1">A </option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>

回答by Madhuka Dilhan

$(document).ready(function() {
  $('#YourID option[value="3"]').attr("selected", "selected");
  $('#YourID option:selected').attr("selected",null);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<select id="YourID">
  <option value="1">A</option>
  <option value="2">B</option>
  <option value="3">C</option>
  <option value="4">D</option>
</select>

回答by Black Mantha

The match between .val('Bruce jones')and value="Bruce Jones"is case-sensitive. It looks like you're capitalizing Jones in one but not the other. Either track down where the difference comes from, use id's instead of the name, or call .toLowerCase()on both.

之间的匹配.val('Bruce jones')value="Bruce Jones"区分大小写。看起来你在一个而不是另一个中大写琼斯。要么找出差异的来源,使用 id 代替名称,要么同时调用.toLowerCase()两者。