最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Selecting an option using fancy select - Stack Overflow

programmeradmin4浏览0评论

I've got a fancy select with code similar to the following, yet adding the selected=selected attribute to one of the options (with JS) does not change which item is currently selected.

<li class="field">
  <div class="picker">
    <select>
      <option value="#" disabled>Favorite Doctor…</option>
      <option>Colin Baker</option>
      <option>Sylvester McCoy</option>
      <option>Paul McGann</option>
      <option>Christopher Eccleston</option>
      <option>David Tennant</option>
      <option>Matt Smith</option>
    </select>
  </div>
</li>

How can I change the selected option and have this change reflected in the select box.

I've got a fancy select with code similar to the following, yet adding the selected=selected attribute to one of the options (with JS) does not change which item is currently selected.

<li class="field">
  <div class="picker">
    <select>
      <option value="#" disabled>Favorite Doctor…</option>
      <option>Colin Baker</option>
      <option>Sylvester McCoy</option>
      <option>Paul McGann</option>
      <option>Christopher Eccleston</option>
      <option>David Tennant</option>
      <option>Matt Smith</option>
    </select>
  </div>
</li>

How can I change the selected option and have this change reflected in the select box.

Share Improve this question asked Mar 5, 2014 at 16:26 jSherzjSherz 9274 gold badges14 silver badges33 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

Try to trigger the change event after you set the selected option, for example:

$('option:eq(2)').prop('selected',true).trigger('change'); // or .change()

Fiddle Demo

Solved it by setting the select.val() to the text of the option I'm trying to select.

I solved it by mending FS's code. It was using :selected as a selector. Changed it to [selected="selected"] and it behaved. Best to just avoid FS pletely though, in my opinion. I inherited it on a project I'm working on.

Around line 56 in my copy, now changed to:

triggerHtml = settings.triggerTemplate(sel.find('[selected="selected"]'));
发布评论

评论列表(0)

  1. 暂无评论