我的下拉列表如下:

<select id="HowYouKnow" >
  <option value="1">FRIEND</option>
  <option value="2">GOOGLE</option>
  <option value="3">AGENT</option></select>

In the above dropdown i know the text of the dropdown. How can set the value of the dropdown in document.ready with the text using jquery?

推荐答案

This is a method that works based on the text of the option, not the index. Just tested.

var theText = "GOOGLE";
$("#HowYouKnow option:contains(" + theText + ")").attr('selected', 'selected');

或者,如果有类似的值(感谢shanabus):

$("#HowYouKnow option").each(function() {
  if($(this).text() == theText) {
    $(this).attr('selected', 'selected');            
  }                        
});

Jquery相关问答推荐

当父迪瓦是重复元素时,如何将一些子元素包裹在父迪瓦中

如何用each替换元素的attr href

为什么函数没有进入

jQueryUI 模态对话框不显示关闭按钮 (x)

jQuery:在mousemove事件期间检测按下的鼠标按钮

Jquery如何通过数组中的属性查找对象

在 CSS3 或 jQuery 中将元素的宽度从 0% 设置为 100% 动画,它和它的包装器只需要它们需要的宽度,没有预先设置的宽度

将一个类动态添加到 Bootstrap 的popover容器中

如何用 javascript/jquery 替换 url 参数?

如何使用 jQuery 重置 jquery Select 的 Select 选项?

显示的 jQuery 日期 Select 器年份

使用 jQuery 获取选定的选项 id

使用 jQuery 将宽度设置为百分比

禁用 jquery Select 的下拉菜单

如何在 Bootstrap 中创建切换按钮

如何使用 javascript 擦除所有内联样式并仅保留 css 样式表中指定的样式?

如何使用 jQuery 取消设置元素的 CSS 属性?

JavaScript 等效于 jQuery 的扩展方法

Chrome 中的 AJAX 发送选项而不是 GET/POST/PUT/DELETE?

在jQuery中,当它们都具有相同的名称时,如何获取单选按钮的值?