Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
401 views
in Technique[技术] by (71.8m points)

javascript - jQuery /以编程方式在“选择”框中选择一个选项(jQuery / Programmatically Select an Option in Select Box)

I'm currently using jQuery to return some JSON results.

(我目前正在使用jQuery返回一些JSON结果。)

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>

And if my JSON value is:

(如果我的JSON值为:)

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

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

(我如何使用jQuery来选择值为'17:00:00'的选项?)

 <option value="17:00:00" selected="selected">5:00 pm</option>
  ask by Dodinas translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

update:

(更新:)

As of jQuery 1.9, jQuery has updated this functionality.

(从jQuery 1.9开始,jQuery已更新了此功能。)

The "selected" state of an option is actually a property, therefore jQuery has changed this to use the .prop() method.

(选项的“选择”状态实际上是一个属性,因此jQuery将其更改为使用.prop()方法。)

Syntax is very similar and easy to switch:

(语法非常相似且易于切换:)

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

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

(有关为什么需要传递true请参见http://api.jquery.com/prop/#entry-longdesc 。)


Older jQuery

(较旧的jQuery)

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

or

(要么)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...