【问题标题】:jQuery disable SELECT options based on Radio selected (Need support for all browsers)jQuery 禁用基于 Radio selected 的 SELECT 选项(需要所有浏览器的支持)
【发布时间】:2009-05-18 11:49:23
【问题描述】:

好的,这里有点麻烦,想在选择收音机时禁用一些选项。选择 ABC 时,禁用 1,2 和 3 选项等...

$("input:radio[@name='abc123']").click(function() {
   if($(this).val() == 'abc') {

      // Disable 
      $("'theOptions' option[value='1']").attr("disabled","disabled");
      $("'theOptions' option[value='2']").attr("disabled","disabled");
      $("'theOptions' option[value='3']").attr("disabled","disabled");

   } else {
      // Disbale abc's
   }    
});

ABC: <input type="radio" name="abc123" id="abc"/>
123: <input type="radio" name="abc123" id="123"/>

<select id="theOptions">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="a">a</option>
  <option value="b">b</option>
  <option value="c">c</option>
</select>

没有任何想法?

更新:

好的,我已经启用/禁用了,但出现了一个新问题。我的选择框的禁用选项仅适用于 FF 和 IE8。我已经测试过 IE6 并且禁用的不工作。我尝试使用 hide() 和 show() 也没有运气。基本上我需要隐藏/禁用/删除选项(适用于所有浏览器),并且如果选择了其他单选选项,则能够将它们添加回来,反之亦然。

结论:

感谢所有解决方案,其中大多数都回答了我最初的问题。给所有人的许多道具:)

【问题讨论】:

标签: jquery


【解决方案1】:

实现您想要的功能的正确方法是删除选项。正如您发现的那样,在浏览器中禁用单个选项并不是特别好。我刚醒来,想编程一些东西,所以我做了一个小插件,可以根据收音机的选定 ID 属性轻松过滤选择。尽管其他解决方案可以完成工作,但如果您计划在整个应用程序中执行此操作,这应该会有所帮助。如果不是,那么我想这是因为其他人偶然发现了这一点。这是您可以隐藏在某处的插件代码:

jQuery.fn.filterOn = function(radio, values) {
    return this.each(function() {
        var select = this;
        var options = [];
        $(select).find('option').each(function() {
            options.push({value: $(this).val(), text: $(this).text()});
        });
        $(select).data('options', options);
        $(radio).click(function() {
            var options = $(select).empty().data('options');
            var haystack = values[$(this).attr('id')];
            $.each(options, function(i) {
                var option = options[i];
                if($.inArray(option.value, haystack) !== -1) {
                    $(select).append(
                    $('<option>').text(option.text).val(option.value)
                    );
                }
            });
        });            
    });
};

这里是如何使用它:

$(function() {
    $('#theOptions').filterOn('input:radio[name=abc123]', {
        'abc': ['a','b','c'],
        '123': ['1','2','3']        
    });
});

第一个参数是无线电组的选择器,第二个参数是字典,其中键是要匹配的无线电 ID,值是应保留的选择选项值的数组。有很多事情可以做进一步抽象,如果你有兴趣,请告诉我,我当然可以做到。

Here is a demo of it in action.

编辑:另外,忘记添加了,根据jQuery documentation

在 jQuery 1.3 中,[@attr] 样式选择器被移除(它们之前在 jQuery 1.2 中已被弃用)。只需从选择器中删除“@”符号即可使其再次工作。

【讨论】:

  • 这正是我所需要的,非常感谢!!!最后一个问题,这是在 document.ready 内部还是外部?
  • 插件代码可以在它之外,只要它在包含jQuery之后。调用它的代码应该像我拥有的​​那样放在文档中,或者放在文档的底部。
  • 谢谢。好的最后一件事。我在代码中使用了一个示例,因此 RegEx 没有按预期工作。我有四个 opiotns 值:BGE BGE_KKI OKE MYF 我的收音机是 P 和 S 我正在尝试这个但没有运气:'P': /('BGE'|'BGE_KKI'|'OKE')/, 'S ': /('MYF')/
  • 你想去掉字母周围的单引号,它应该可以工作,即:(BGE|BGE_KKI|OKE)
  • 顺便说一句,如果您希望匹配的只是一组单独的值,那么将它作为数组传递可能是最干净的,例如,'P': [' BGE','BGE_KKI','OKE'] - 如果你对此感兴趣,我可以为它修改插件。
【解决方案2】:

你想要这样的东西 - Example Code here

$(function() {

$("input:radio[@name='abc123']").click(function() {
   if($(this).attr('id') == 'abc') {

      // Disable 123 and Enable abc
      $("#theOptions option[value='1']").attr("disabled","disabled");
      $("#theOptions option[value='2']").attr("disabled","disabled");
      $("#theOptions option[value='3']").attr("disabled","disabled");
      $("#theOptions option[value='a']").attr("selected","selected");
      $("#theOptions option[value='a']").attr("disabled","");
      $("#theOptions option[value='b']").attr("disabled","");
      $("#theOptions option[value='c']").attr("disabled","");

   } else {
      // Disable abc's and Enable 123
      $("#theOptions option[value='a']").attr("disabled","disabled");
      $("#theOptions option[value='b']").attr("disabled","disabled");
      $("#theOptions option[value='c']").attr("disabled","disabled");
      $("#theOptions option[value='1']").attr("selected","selected");          
      $("#theOptions option[value='1']").attr("disabled","");   
      $("#theOptions option[value='2']").attr("disabled","");
      $("#theOptions option[value='3']").attr("disabled","");

   }    
});

});

编辑:

代码的改进版本,使用正则表达式根据选项值过滤选项。 Working example here。您可以通过将 /edit 添加到 URL 来编辑示例

$(function() {

    $("input:radio[@name='abc123']").click(function() {

        // get the id of the selected radio
        var radio = $(this).attr('id'); 

        // set variables based on value of radio
        var regexDisabled = radio == 'abc' ?  /[1-3]/ : /[a-c]/;      
        var regexEnabled = radio == 'abc' ? /[a-c]/ : /[1-3]/;
        var selection = radio == 'abc' ? 'a' : 1;

        // select all option elements who are children of id #theOptions
        $("#theOptions option")
            // filter the option elements to only those we want to disable
            .filter( function() { return this.value.match(regexDisabled);})
            // disable them
            .attr("disabled","disabled")
            // return to the previous wrapped set i.e. all option elements
            .end()
            // and filter to those option elements we want to enable
            .filter( function() { return this.value.match(regexEnabled);})
            // enable them
            .attr("disabled","");
       // change the selected option element in the dropdown
       $("#theOptions option[value='" + selection + "']").attr("selected","selected");

    });

});

编辑 2:

由于 disabled 属性似乎不能在浏览器中可靠地工作,我认为您唯一的选择是删除选择单选按钮时不需要的选项元素。 Working Example here

  $(function() {

        $("input:radio[@name='abc123']").click(function() {

            // store the option elements in an array
            var options = [];
            options[0] = '<option value="1">1</option>';
            options[1] = '<option value="2">2</option>';
            options[2] = '<option value="3">3</option>';
            options[3] = '<option value="a">a</option>';
            options[4] = '<option value="b">b</option>';
            options[5] = '<option value="c">c</option>';


            var radio = $(this).attr('id');   
            var regexEnabled = radio == 'abc' ? /[a-c]/ : /[1-3]/;

            // set the option elements in #theOptions to those that match the regular expression
            $("#theOptions").html(
            $(options.join(''))
                // filter the option elements to only those we want to include in the dropdown
                .filter( function() { return this.value.match(regexEnabled);})
            );


        });

    });

甚至

  $(function() {

        // get the child elements of the dropdown when the DOM has loaded
        var options = $("#theOptions").children('option');

        $("input:radio[@name='abc123']").click(function() {         

            var radio = $(this).attr('id');   
            var regexEnabled = radio == 'abc' ? /[a-c]/ : /[1-3]/;

            // set the option elements in #theOptions to those that match the regular expression
            $("#theOptions").html(
            $(options)
                // filter the option elements to only those we want to include in the dropdown
                .filter( function() { return this.value.match(regexEnabled);})
            );

        }); 
    });

【讨论】:

  • 另一个问题,太棒了!看原题+EDIT。谢谢:)
  • 我正在尝试这个,但是在选择其他选项时如何添加已删除的元素(例如来回切换)。另外我如何检查重复项?再次感谢在这个问题上的所有帮助。
  • 这由正则表达式匹配处理,可以针对数组中的选项元素(倒数第二个代码示例),或者针对 DOM 加载时在变量中捕获的选项元素(最终代码示例)。跨度>
  • 这看起来是最好的解决方案,但由于浏览器问题,它对我不起作用。感谢您的努力
  • 附加的选项元素可以跨浏览器工作,但 Paolo 将功能包装在插件中的想法是正确的
【解决方案3】:

第一个问题是

$(this).val()

替换为

$(this).attr('id') == 'abc'

这样就不行了

$("'theOptions'..")

使用

$("#theOptions option[value='1']").attr('disabled','disabled') //to disable
$("#theOptions option[value='a']").attr('disabled','') //to ENABLE

【讨论】:

  • 这是有效的,但有一个后续问题。如何选择启用的选项?
  • Phill 如果您的意思是如何启用选项,最后一行(以注释//to Enable 结尾)可以解决问题。如果不是这样,我不明白:(
  • 我看到了,但我想要的是在下拉列表中选择一个启用选项。禁用选项时,即使已禁用,所选选项仍处于启用状态,直到您选择启用的选项。那么您将无法再次选择它。抱歉,这有意义吗?因此,如果我禁用 abs 并且在 a 上预先选择了该选项,则 a 仍然处于启用状态,直到我重新选择一个新的启用选项。
  • 酷谢谢让我试一试。另一个问题已经暴露出来。请阅读原始问题的编辑版本。顺便说一句,感谢所有帮助和反馈很多道具:)
【解决方案4】:

您使用的是哪个浏览器?我以前从未使用过它,但在 IE8 之前的 IE 中似乎不支持它。有关详细信息,请参阅此链接:

http://www.w3schools.com/TAGS/att_option_disabled.asp

【讨论】:

  • 我将不得不对此进行调查。我正在使用 FF3 但仍需要测试 IE[6-8]
  • 另一个问题,太棒了!看原题+EDIT。谢谢 :) 还有其他想法吗?
  • 认为我找到了解决问题的好方法,再次感谢您指出这一点,让我免于遇到麻烦。 =P
【解决方案5】:

您的选择器错误。而不是

$("'theOptions' option[value='1']")

你应该使用

$("#theOptions > option[value='1']")

另请参阅 jQuery selectors documentation。看看 aman.tur 的suggestion

【讨论】:

  • 另一个问题,太棒了!看原题+EDIT。谢谢:)
【解决方案6】:
$(":radio[name=abc123]").click(function() {
   var $options = $("#theOptions")
   var toggle = ($(this).val() == 'abc') ? true : false;

   $("[value=1],[value=2],[value=3]", $options).attr("disabled", toggle);
   $("[value=a],[value=b],[value=c]", $options).attr("disabled", !toggle);
});

【讨论】:

  • 另一个问题,太棒了!看原题+EDIT。谢谢:)
【解决方案7】:

如果你想禁用某些选项,下面的代码应该可以工作

$("input:radio[name='abc123']").click(function() {
   var value = $(this).val();

   $("option[value='1'], option[value='2'], option[value='3']", "#theOptions").each(function(){
      this.disabled = value == 'abc';
   });
   $("option[value='a'], option[value='b'], option[value='c']", "#theOptions").each(function(){
      this.disabled = value == '123';
   })
});

和单选按钮

ABC: <input type="radio" name="abc123" value="abc" id="abc"/>
123: <input type="radio" name="abc123" value="123" id="123"/>

如果您想从选择列表中删除选项,请使用此代码

$(function(){
   var options = null;
   $("input:radio[name='abc123']").click(function() {
      var value = $(this).val();
      if(options != null)options.appendTo('#theOptions');
      if(value == 'abc' )
         options = $("option[value='1'], option[value='2'], option[value='3']", "#theOptions").remove();
      else if(value == '123')
         options = $("option[value='a'], option[value='b'], option[value='c']", "#theOptions").remove();
   });
});

顺便说一句。我的代码使用 jQuery (1.3.2) 的当前稳定版本。如果您使用的是旧版本,则需要将属性选择器更改为旧语法。

option[value='1'] 到 option[@value='1']

【讨论】:

  • 另一个问题,太棒了!看原题+EDIT。谢谢:)
  • 编辑了我的整个帖子。查看新的代码示例。现在,它应该可以正常工作了。
  • 看起来不错,但现在如果用户选择其他单选选项以及处理重复项,我该如何添加已删除的选项。再次感谢您对此的帮助:)
  • 我的代码使用 if(options != null)options.appendTo('#theOptions');) 再次插入所有已删除的选项。重新插入选项后,它会检查选择了哪个单选按钮并删除其他选项。也不应该出现任何重复。如果我确实理解错了您的问题,请尝试用其他方式解释它,也许我可以提供更多帮助。
【解决方案8】:

只需将选择器 $("'theOptions' option[value='1']") 修复为 $("#theOptions option[value='1']") 一切都会好起来的

【讨论】:

    猜你喜欢
    • 2010-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-14
    • 2011-08-26
    • 1970-01-01
    • 2012-12-03
    • 1970-01-01
    相关资源
    最近更新 更多