Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 设置列表框中选中值的限制_C#_Jquery_Asp.net - Fatal编程技术网

C# 设置列表框中选中值的限制

C# 设置列表框中选中值的限制,c#,jquery,asp.net,C#,Jquery,Asp.net,我有多个选择列表框,我想限制用户选择3个以上的值。这些值可以是国家或城市,它们来自数据库。相同的代码是用lstArea_SelectedIndexChanged方法编写的 我发现jquery代码验证了相同的功能,但change函数不起作用 var limit = 3; $("#<%=lstArea.ClientID%>").change(function () { if ($(this).siblings(':checked').length >

我有多个选择列表框,我想限制用户选择3个以上的值。这些值可以是国家或城市,它们来自数据库。相同的代码是用lstArea_SelectedIndexChanged方法编写的


我发现jquery代码验证了相同的功能,但change函数不起作用

    var limit = 3;
    $("#<%=lstArea.ClientID%>").change(function () {
        if ($(this).siblings(':checked').length >= limit) {
            this.checked = false;
        }
    });

我想这个地址可以帮助你 也许你应该代替

 if ($(this).siblings(':checked').length >= limit)
这个


由于您已将属性AutoPostBack设置为true,并且还设置了OnSelectedIndexChanged事件处理程序,.NET将为您的select生成onchange属性,每当选择一个项目时,该属性将触发回发到服务器。要防止出现这种情况,您需要将.NET代码更改为:

<asp:ListBox ID="lstArea" runat="server" SelectionMode="Multiple"/>
// Handle for the list
var list = $("#<%=lstArea.ClientID%>");

// Our limit
var limit = 3;

// Get currently selected values
var selected = list.val();

// Handle change event
list.change(function () {
    // If we reached the limit
    if (list.find(":checked").length >= limit) {
        // Set the list value back to the previous ones
        list.val(selected);
        return;
    }

    // Postback to the server
    setTimeout("__doPostBack('<%=lstArea.ClientID%>','')", 0);
});
并将javascript代码更新为:

<asp:ListBox ID="lstArea" runat="server" SelectionMode="Multiple"/>
// Handle for the list
var list = $("#<%=lstArea.ClientID%>");

// Our limit
var limit = 3;

// Get currently selected values
var selected = list.val();

// Handle change event
list.change(function () {
    // If we reached the limit
    if (list.find(":checked").length >= limit) {
        // Set the list value back to the previous ones
        list.val(selected);
        return;
    }

    // Postback to the server
    setTimeout("__doPostBack('<%=lstArea.ClientID%>','')", 0);
});

每次呈现页面时,所选变量将保存最后选定的项目。在更改处理程序中,您将获得所有选定/选中的选项,当新选定选项的计数大于或等于您的限制时,您将通过设置所有以前的值来取消选择最后选定的值。如果限制没有问题,您将通过调用.NET函数uu doPostBack来进行回发。

以上3个值未包含在您的问题中。请在提交之前完成您的问题。更改功能不起作用。if语句是否没有返回您期望的结果?或者如果this.checked没有做你期望的事情?@KSib当我调试这个时,控件没有进入function@Thomas我已经编辑了这个问题。你看过我的答案了吗?