4 L*_*ver 9 javascript asp.net
我正在使用ASP.NET,并希望在客户端执行以下操作,因为我不希望页面重新加载(不想要回发).我想检查以下条件的用户输入:
我注意到我的按钮已经进入<asp:button>
,<input type="submit>
因此它不会将我的代码运行到服务器上.如果我错了,请纠正我.那么如何在不必<asp:button>
传递给服务器的情况下验证用户输入呢?
小智 18
你可以试试:
<asp:button onClientClick="return validateData();">
Run Code Online (Sandbox Code Playgroud)
在JavaScript中它应该是:
function validateData() {
if (OK) {
return true;
} else {
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
return true
将使您的页面回发到服务器,并return false
阻止您的页面这样做.希望这可以帮助.
处理验证,我会使用ASP.net自定义验证器并使用jquery来辅助客户端验证:
ASP.net aspx
<form id="form1" runat="server">
<div>
<div id="requiedCheck1" class="check">
<asp:RadioButton ID="radio1" runat="server" GroupName="myGroup" />
<asp:TextBox ID="text1" runat="server" Disabled="true"></asp:TextBox>
<asp:CustomValidator
ID="val1" runat="server" ErrorMessage="Please Enter Text" ClientValidationFunction="ValidateSomething" ControlToValidate="text1" ValidateEmptyText="true" ></asp:CustomValidator>
</div>
<div id="requiedCheck2" class="check">
<asp:RadioButton ID="radio2" runat="server" GroupName="myGroup" />
<asp:TextBox ID="text2" runat="server" Disabled="true"></asp:TextBox>
<asp:CustomValidator
ID="CustomValidator1" runat="server" ErrorMessage="Please Enter Text" ClientValidationFunction="ValidateSomething" ControlToValidate="text2" ValidateEmptyText="true"></asp:CustomValidator>
</div>
<asp:button ID="Button1" runat="server" text="Button" />
</div>
</form>
Run Code Online (Sandbox Code Playgroud)
请注意,我已设置ValidateEmptyText
为true
.
js验证功能
function ValidateSomething(sender, args) {
args.IsValid = false;
var parentDiv = $(sender).parent(".check");
var radioChecked = $(parentDiv).find("input:radio").is(":checked");
var hasText = $(parentDiv).find("input:text").val().length > 0;
if (radioChecked) {
args.IsValid = hasText;
} else {
args.IsValid = true;
}
}
Run Code Online (Sandbox Code Playgroud)
我也会添加服务器端验证方法.
如果你想真正想要你也应该能够连接单选按钮.这将在检查无线电按钮时触发验证
$(document).ready(function () {
//Wire up the radio buttons to trigger validation this is optional
$(".check input:radio").each(function () {
ValidatorHookupControlID($(this).attr('id'), document.getElementById("<%= val1.ClientID %>"));
ValidatorHookupControlID($(this).attr('id'), document.getElementById("<%= val2.ClientID %>"));
});
//jquery to change the disabled state
$(".check :radio").click(function(){
var parDiv = $(this).parent(".check"); //get parent div
//empty text and set all to disabled
$(".check input:text").val("").prop("disabled", true);
//set target to enabled
$(parDiv).find("input:text").prop("disabled", false);
});
});
Run Code Online (Sandbox Code Playgroud)
我添加了jQuery javascript来切换文本框的禁用状态.您可以在此处看到切换操作:http://jsfiddle.net/cVACb/
归档时间: |
|
查看次数: |
40727 次 |
最近记录: |