jQuery 如何让用户在复选框列表中只选择一个复选框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1818102/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:11:55  来源:igfitidea点击:

how to make user select only one check box in a checkboxlist

asp.netjquery

提问by happysmile

i have an check boxlist with (6 items under it). and i have an search button. if user clicks Search button it gets all the result. i am binding the items for checkboxlist using database in .cs file

我有一个复选框列表(下面有 6 个项目)。我有一个搜索按钮。如果用户单击“搜索”按钮,它将获得所有结果。我正在使用 .cs 文件中的数据库绑定复选框列表的项目

condition1:but now if user selects a checkbox[item1] its gets selected and he tries to select an 2 checkbox[item2] then firstselected checkbox[item1] should be unselected. only checkbox[item2] should be selected

条件 1:但是现在如果用户选择一个复选框 [item1] 它被选中并且他试图选择一个 2 复选框 [item2] 那么 firstselected 复选框 [item1] 应该被取消选中。只应选中复选框[item2]

condition 2:now if user as selected checkbox1 [item1] it gets selected. and now if user again clicks on checkboxi[item1] then it should get deselected.

条件 2:现在如果用户被选中 checkbox1 [item1] 它被选中。现在如果用户再次点击 checkboxi[item1] 那么它应该被取消选择。

either you can provide me the solution in javascript or JQuery any help would be great . looking forward for an solution thank you

您可以在 javascript 或 JQuery 中为我提供解决方案,任何帮助都会很棒。期待解决方案谢谢

回答by Richie

use Radio button. The only problem you will face is when you want to de-select the radio button. You can write in a javascript for 'onClick' of radio button. The onClick function can check whether radio button is selected, if it is not select it else deselect it.

使用单选按钮。您将面临的唯一问题是何时要取消选择单选按钮。您可以为单选按钮的“onClick”编写 javascript。onClick 函数可以检查单选按钮是否被选中,如果没有选中则取消选中它。

Hope this helps. See Example

希望这可以帮助。见示例

RDJ

RDJ

回答by jkody21

While I definitely agree with the consensus that radio buttons are the way to go for your described use-case, here is a little snipped of jquery that will cause checkboxes to behave like radio buttons. You simply need to add a "groupname" attribute to your checkbox tag.

虽然我绝对同意单选按钮是您描述的用例的方式这一共识,但这里有一些 jquery 片段,它将导致复选框的行为类似于单选按钮。您只需将“组名”属性添加到您的复选框标签。

HTML:

HTML:

<fieldset>
<legend>Group 1 - radio button behavior</legend>
<input type="checkbox" groupname="group1" value="1" /> Checkbox 1<br />
<input type="checkbox" groupname="group1" value="2" /> Checkbox 2<br />
<input type="checkbox" groupname="group1" value="3" /> Checkbox 3<br />
<input type="checkbox" groupname="group1" value="4" /> Checkbox 4<br />
<input type="checkbox" groupname="group1" value="5" /> Checkbox 5<br />
</fieldset>


<fieldset>    
<legend>Group 2 - radio button behavior</legend>
<input type="checkbox" groupname="group2" value="1" /> Checkbox 1<br />
<input type="checkbox" groupname="group2" value="2" /> Checkbox 2<br />
<input type="checkbox" groupname="group2" value="3" /> Checkbox 3<br />
<input type="checkbox" groupname="group2" value="4" /> Checkbox 4<br />
<input type="checkbox" groupname="group2" value="5" /> Checkbox 5<br />
</fieldset>

<fieldset>    
<legend>Group 3 normal checkbox behavior</legend>
<input type="checkbox" value="1" /> Checkbox 1<br />
<input type="checkbox" value="2" /> Checkbox 2<br />
<input type="checkbox" value="3" /> Checkbox 3<br />
<input type="checkbox" value="4" /> Checkbox 4<br />
<input type="checkbox" value="5" /> Checkbox 5<br />
</fieldset>

Javascript:

Javascript:

    <script type="text/javascript">
    $(document).ready(function() {
        $('input[type=checkbox]').click(function() {
        var groupName = $(this).attr('groupname');

            if (!groupName)
                return;

            var checked = $(this).is(':checked');

            $("input[groupname='" + groupName + "']:checked").each(function() {
                $(this).prop('checked', '');
            });

            if (checked)
                $(this).prop('checked', 'checked');
        });
    });
</script>

I'm sure there are opportunities to increase brevity and performance, but this should get you started.

我确信有机会提高简洁性和性能,但这应该让你开始。

回答by Mahesh Velaga

Why don't you use radio buttons, they are ideal for the purpose that you mentioned.

为什么不使用单选按钮,它们非常适合您提到的目的。

Edit:

编辑:

If you necessarily want to use checkbox list then assign some logical ids to those checkboxes so that you can access them in JavaScript. On each onclick event of the checkboxes call the JavaScript and in the JavaScript loop through and see

如果您一定要使用复选框列表,则为这些复选框分配一些逻辑 ID,以便您可以在 JavaScript 中访问它们。在复选框的每个 onclick 事件上调用 JavaScript 并在 JavaScript 循环中查看

  • If any checkbox is checked other than the present clicked checkbox, then make them unselected.
  • If the present checkbox is already checked then just toggle it.
  • 如果选中当前单击的复选框以外的任何复选框,则取消选中它们。
  • 如果当前复选框已被选中,则只需切换它。

You can see if a checkbox is checked using $("#checkboxId").is(":checked")which returns true if a checkbox is checked.

您可以使用如果复选框被选中$("#checkboxId").is(":checked")则返回 true 来查看复选框是否被选中。

Thanks

谢谢

回答by happysmile

this was the code that helped me to solve this issue

这是帮助我解决这个问题的代码

just add the script -

只需添加脚本 -

var objChkd;

var objChkd;

function HandleOnCheck() {

函数 HandleOnCheck() {

var chkLst = document.getElementById('CheckBoxList1'); if(objChkd && objChkd.checked)

var chkLst = document.getElementById('CheckBoxList1'); 如果(objChkd && objChkd.checked)

      objChkd.checked=false;objChkd = event.srcElement; 

}

}

and register the client event to the 'CheckBoxList1' at the Page_load as

并将客户端事件注册到 Page_load 处的“CheckBoxList1”作为

CheckBoxList1.Attributes.Add("onclick","return HandleOnCheck()");

CheckBoxList1.Attributes.Add("onclick","re​​turn HandleOnCheck()");

回答by PhilPursglove

You might want to have a look at the MutuallyExclusiveCheckBoxExtender.

您可能想看看MutuallyExclusiveCheckBoxExtender

回答by Etienne Dupuis

.aspx

.aspx

<asp:CheckBoxList id="chkList" runat="server" RepeatLayout="Flow" />

.js

.js

$(document).ready(function () {
    LimitCheckboxes('input[name*=chkList]', 3);
}



function LimitCheckboxes(control, max) {

    $(control).live('click', function () {

        //Count the Total Selection in CheckBoxList 
        var totCount = 1;
        $(this).siblings().each(function () {
            if ($(this).attr("checked")) { totCount++; }
        });

        //if number of selected item is greater than the max, dont select.
        if (totCount > max) { return false; }
        return true;
    });

}

PS: Make sure you use the RepeatLayout="Flow" to get rid of the annoying table format.

PS:确保您使用 RepeatLayout="Flow" 摆脱烦人的表格格式。

回答by hero3616

My jQuery solution for this is coded as follows:

我对此的 jQuery 解决方案编码如下:

$(document).ready(function () {
    SetCheckboxListSingle('cblFaxTypes');
});

function SetCheckboxListSingle(cblId) {
    $('#' + cblId).find('input[type="checkbox"]').each(function () {
        $(this).bind('click', function () {
            var clickedCbxId = $(this).attr('id');
            $('#cblFaxTypes').find('input[type="checkbox"]').each(function () {
                if (clickedCbxId == $(this).attr('id'))
                return true;
               // do not use JQuery to uncheck the here because it breaks'defaultChecked'property
                // http://bugs.jquery.com/ticket/10357
                document.getElementById($(this).attr('id')).checked = false;

            });
        });
    });
}

回答by Bhaskarreddy Mule

we can do in java script to get the solution for this.

我们可以用java脚本来解决这个问题。

For this first get the id of the checked item and go thorough the remaining items using loop then unchecked the remaining items

为此,首先获取已检查项目的 id,然后使用循环遍历剩余项目,然后取消选中剩余项目

http://csharpektroncmssql.blogspot.com/2011/11/uncheck-check-box-if-another-check-box.html

http://csharpektroncmssql.blogspot.com/2011/11/uncheck-check-box-if-another-check-box.html

回答by Jesuraja

Try this solution:

试试这个解决方案:

Code Behind (C#) :

代码隐藏(C#):

foreach (ListItem listItem in checkBoxList.Items)
{
    listItem.Attributes.Add("onclick", "makeSelection(this);");
}

Java Script :

Java脚本:

function makeSelection(checkBox)
{
    var checkBoxList = checkBox;
    while (checkBoxList.parentElement.tagName.toLowerCase() != "table")
    {
        checkBoxList = checkBoxList.parentElement;
    }

    var aField = checkBoxList.getElementsByTagName("input");
    var bChecked = checkBox.checked;

    for (i = 0; i < aField.length; i++)
    {
        aField[i].checked = (aField[i].id == checkBox.id && bChecked);
    }
}