gpt4 book ai didi

javascript - 使用vb从asp.net中的列表框中限制项目选择

转载 作者:行者123 更新时间:2023-11-29 15:47:12 24 4
gpt4 key购买 nike

我想使用 vb 限制从 asp.net 中的列表框中选择的项目数。我正在尝试使用 javascript。但是,不工作。需要帮助

<asp:ListBox ID="lbprefferedlocation" runat="server" DataSourceID="locations" 
DataTextField="City_Name" OnSelectedIndexChanged="chkCount(this)" DataValueField="City_Name" SelectionMode="Multiple"></asp:ListBox>
<asp:HiddenField ID="hiddenChkCount" runat="server" />
<asp:SqlDataSource ID="locations" runat="server"
ConnectionString="<%$ ConnectionStrings:JPConnString %>"
SelectCommand="SELECT [City_Name] FROM [State_Info]"></asp:SqlDataSource>



function chkCount(obj)
{
if(obj.checked==true)
{
if( document.getElementById( '<%=hiddenChkCount.ClientID %>' ).value >= 5 )
{
alert('You cannot select more than 5 items.');
obj.checked=false;
}
else
{
document.getElementById( '<%=hiddenChkCount.ClientID %>' ).value = parseInt( document.getElementById( '<%=hiddenChkCount.ClientID %>' ).value ) + 1;
}
}
else
{
document.getElementById( '<%=hiddenChkCount.ClientID %>' ).value = parseInt( document.getElementById( '<%=hiddenChkCount.ClientID %>' ).value) - 1;
}
}

最佳答案

您可以使用 CustomValidator:

 <asp:CustomValidator ID="CV_CheckLocationCount" runat="server"
ValidateEmptyText="true"
ClientValidationFunction="CheckLocationCount"
OnServerValidate="CheckLocationCount"
ControlToValidate="lbprefferedlocation"
EnableClientScript="true"
ErrorMessage="Select at least one and at most 5 locations"
ValidationGroup="VG_SAVE">*
</asp:CustomValidator>

function CheckLocationCount(sender, args){
var count=$('#<%=lbprefferedlocation.ClientID %> option:selected').length;
args.IsValid = count > 0 && count <= 5;
}

编辑:这是一个非 jQuery 解决方案:

function validateListBoxSelectionCount(listbox, minSelected, maxSelected){
var selected=0;
if(listbox != null){
for (var i=0; i<listbox.length; i++){
if(listbox.options[i].selected){
selected++;
if(selected>maxSelected)break;
}
}
}
return (selected >= minSelected && selected <= maxSelected);
}

你可以这样使用它:

var listBox  = document.getElementById("<%=lbprefferedlocation.ClientID %>");
args.IsValid = validateListBoxSelectionCount(listBox, 1, 5);

关于javascript - 使用vb从asp.net中的列表框中限制项目选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10010544/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com