【问题标题】:Limiting radio button selection across groups限制跨组的单选按钮选择
【发布时间】:2020-05-10 00:13:27
【问题描述】:

我知道如何限制用户可以选择的复选框数量,但不知道如何使用多组单选按钮来做到这一点。

这就是场景。第一组单选按钮允许用户选择一个数字 - 从 1 到 6。我得到的值是这样的:

    $('#input_3_1 input').on('change', function() {
    var selectedVal = "";
    var selected = $("#input_3_1 input[type='radio']:checked");
    if (selected.length > 0) {
        selectedVal = selected.val();
    }
    });  

之后是一系列单选组,每个组都有多个选项,如下所示:

    <div id="input_3_2" class="limit-this">
    <input name="input_2" type="radio" value="Choice 1">
    <input name="input_2" type="radio" value="Choice 2">
    <input name="input_2" type="radio" value="Choice 3">
    </div>

    <div id="input_3_3" class="limit-this">
    <input name="input_3" type="radio" value="Choice 1">
    <input name="input_3" type="radio" value="Choice 2">
    <input name="input_3" type="radio" value="Choice 3">
    </div>

对于可变数量的字段以此类推,最多可达 10 个。

我需要用户能够在所有其他字段中仅选择第一个字段中选择的选项数。

任何人都可以在这里指出正确的方向吗?

【问题讨论】:

  • 无法取消选中单选组中的所有选项。如果用户达到限制,然后想要取消选中其中一个旧组以便他可以从另一个组中选择一些东西,他应该怎么做?
  • 是的,一旦我开始工作,我就意识到这将是一个问题。谢谢你提出来。

标签: jquery radio-button limit


【解决方案1】:
$('.limit-this input[type="radio"]').click(function(){
    var a = $('.limit-this input[type="radio"]:checked').length;
    if(a>selectedVal) if($(this).is(':checked')) $(this).removeAttr('checked');
});

见DEMO

在DEMO2 中,我已启用取消选中当前选中的项目,以防用户改变主意并想要做出另一个选择:

$('.limit-this input[type="radio"]').click(function(){
    var a = $('.limit-this input[type="radio"]:checked').length;
    var b = ($(this).is(':checked')?1:0);
    if(a>selectedVal){ if($(this).is(':checked')){ $(this).removeAttr('checked');}}
    else{

     if($(this).is(':checked')&&$(this).data('val')==1) {$(this).removeAttr('checked');
         $(this).data('val', 0);  
     }else
       $(this).data('val', b);    
    }

});

【讨论】:

  • 我编辑了我的代码并添加了一个演示,请看一下
  • 这绝对是完美的!感谢您不厌其烦地创建演示,它真的很有帮助。
  • 不客气。您是否需要像 cmets 中提到的 Barmar 那样为用户启用取消选中功能?
  • @Katherine 我添加了另一个演示,使用户能够取消选中项目并更改他/她的决定
  • 你是通灵者吗?我只是想弄清楚如何做到这一点!
猜你喜欢
  • 1970-01-01
  • 2017-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-26
  • 2017-02-14
  • 1970-01-01
相关资源
最近更新 更多