【问题标题】:Disable an option, on selecting other option in multiselect在多选中选择其他选项时禁用一个选项
【发布时间】:2018-10-20 03:40:31
【问题描述】:

我在 html 中有一个多选,如下所示。我试图在选择 All Types 时禁用所有选项,并在选择任何其他(一个或多个)选项时禁用 All Types。页面加载时,默认选择All Types选项,用户可以稍后更改。 html 看起来像:

<select multiple="multiple" class="multiselect">
    <option value="default" selected="selected">All Types</option>
    <option value="Mobile">Mobile</option>
    <option value="Laptop">Laptop</option>
    <option value="Desktop">Desktop</option>
</select>    

而 Jquery 为:

$(".multiselect").multiselect({
    buttonWidth: '150px',
    onChange:function(){
     /*some code needed here*/
    }
}); 

选择“所有类型”时,结果应为 ['Mobile','Laptop','Desktop']['default'] 以及如果有的话选择其他选项(一个或多个),然后选择数组中的该值。我在禁用 UI 上的选项时遇到了一些问题。期待解决这个问题的解决方案。在此先感谢:)

【问题讨论】:

    标签: jquery html html-select jquery-multiselect


    【解决方案1】:

    条件是“如果值“默认”被选中”:

    if($(this).val() == "default")
    

    之后,您只需要禁用或启用选项,您可以通过普通的 jQuery 来完成。

    $("option[value='Mobile']").prop("disabled", true);
    

    【讨论】:

      【解决方案2】:

      尝试使用以下更改事件

      $('select').on('change',function(){
      $(this).find('option').prop("disabled", false);//enable all
      if($(this).find('option:selected').is('option[value="default"]')) {}
        $(this).find('option:not(":selected")').prop("disabled", true);
      })
      

      【讨论】:

      • 我试过这个,它抛出一个错误 - “ReferenceError: option is not defined”
      • 这可能适用于正常选择。问题是针对 Jquery 多选
      【解决方案3】:

      为了响应madalinivacsu。

      如果您使用选择插件不要忘记添加触发器:

      $('[name=option_element]').on('change', function () {
              $(this).find('option').prop("disabled",false).trigger('chosen:updated');//enable all
              if ($(this).find('option:selected').is('option[value="option_default"]')) {
                  $(this).find('option:not(":selected")').prop("disabled", true).trigger('chosen:updated');
              }
          });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-08-13
        • 2014-07-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多