【问题标题】:jQuery changing SELECT not working properlyjQuery 更改 SELECT 无法正常工作
【发布时间】:2013-05-09 21:37:58
【问题描述】:

(使用 jquery 移动版) 我有一个重置按钮,需要将所有下拉框 selectedIndex 重置为 0。我相信索引回到零,但选择框上显示的值不正确。它保持相同的值。

这是JSfiddle

例如:选择“unit2”,然后单击重置。单击确定。选择框上显示的值是“unit2”,而应该是“--Units--”

HTML

<div data-role="fieldcontain" class='seltype' id='xmep' >
  <select id="dmep" data-mini='true'>
    <option value="0">--Units--</option>
    <option value='1'>unit1</option>
    <option value='0.01'>unit2</option>
    <option value='10'>unit3</option>
  </select>
</div>

.

.

JQUERY

$(document).ready(function() {
  $('#rstBtn').click(function() {
     var answer = confirm('Click OK to set the selectIndex equal to 0');

        if (answer == false) {
            return;
        } else {
            $('select').prop('selectedIndex', 0);
        }
  });

});

【问题讨论】:

  • 你不需要抓取选中的索引...值为0,所以....$('select').val(0)...and bam
  • @bagofmilk 你需要刷新select。检查我的答案
  • 知道了。感谢您的澄清

标签: jquery select


【解决方案1】:

您需要使用.selectmenu('refresh',true) 刷新选择菜单。

Demo

$(document).ready(function() {
  $('#rstBtn').on('click', function() {
     if (confirm('Click OK to set the selectIndex equal to 0')) {
         $('#dmep').val(0).selectmenu('refresh',true);
         
     }
  });
});

这样会更准确

  $('#dmep').find('option[value="0"]')
  .prop('selected', true).addBack()
   .selectmenu('refresh', true);

   $('#dmep').prop('selectedIndex', 0)
   .selectmenu('refresh', true);

【讨论】:

  • @bagofmilk 检查我的更新,这是更精确的方法。
  • 我花了几个小时才找到这个解决方案...谢谢!
【解决方案2】:

以这种方式工作:http://jsfiddle.net/bWdGB/

使用此方法重置选择框:

$('select').val('0').attr('selected', true).siblings('option').removeAttr('selected');
$('select').selectmenu("refresh", true);

【讨论】:

    猜你喜欢
    • 2018-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-30
    • 2018-10-23
    • 1970-01-01
    相关资源
    最近更新 更多