jQuery/以编程方式在选择框中选择一个选项 [英] jQuery / Programmatically Select an Option in Select Box

查看:31
本文介绍了jQuery/以编程方式在选择框中选择一个选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用 jQuery 返回一些 JSON 结果.返回这些结果后,我将使用它们预先填充表单中的字段.

I'm currently using jQuery to return some JSON results. Once these results are returned, I'm using them to pre-populate fields in my form.

但是,我需要一些帮助来预选下拉框中的项目.例如,我有一个选择框(这是缩短的):

However, I need some help in pre-selecting items in a drop down box. For example, I have a select box (this is shortened):

<select id="startTime">
<option value="14:00:00">2:00 pm</option>
<option value="15:00:00">3:00 pm</option>
<option value="16:00:00">4:00 pm</option>
<option value="17:00:00">5:00 pm</option>
<option value="18:00:00">6:00 pm</option>
</select>

如果我的 JSON 值是:

And if my JSON value is:

 var start_time = data[0].start  // Let's say this is '17:00:00'

如何使用 jQuery 选择值为17:00:00"的选项?

How can I, using jQuery, make the option with value '17:00:00' selected?

 <option value="17:00:00" selected="selected">5:00 pm</option>

推荐答案

更新:

从 jQuery 1.9 开始,jQuery 更新了此功能.选项的选择"状态实际上是一个属性,因此 jQuery 已将其更改为使用 .prop() 方法.语法非常相似且易于切换:

As of jQuery 1.9, jQuery has updated this functionality. The "selected" state of an option is actually a property, therefore jQuery has changed this to use the .prop() method. Syntax is very similar and easy to switch:

$('#startTime option[value=17:00:00]').prop('selected', true);

参见 http://api.jquery.com/prop/#entry-longdesc 为什么它需要传递 true.

See http://api.jquery.com/prop/#entry-longdesc for why it needs to pass true.

较旧的 jQuery

$('#startTime option[value=17:00:00]').attr('selected', 'selected');

$('#startTime option[value='+ data[0].start +']').attr('selected', 'selected');

这篇关于jQuery/以编程方式在选择框中选择一个选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆