我有一个 asp.net 按钮,它具有单击事件,基本上将数据添加到数据库中。我还有一个单选按钮列表(即批准/拒绝)和一个文本框。如果用户选择拒绝,则文本框变为可见。我想运行验证,当用户单击提交按钮时,如果选择拒绝,则文本框不能为空。我已经为此使用了 jquery 验证。当我单击按钮时,消息会出现在文本框旁边,表明该字段是必需的,但它不会停止执行后面的代码。即它将数据添加到数据库中。这是我的代码。
<script type="text/javascript" language="javascript">
$(function() {
$('#declinediv').hide();
////////
var $radBtn = $("table.rblist input:radio");
$radBtn.click(function() {
var $radChecked = $(':radio:checked');
var value = $radChecked.val();
if (value == 'Decline' || value == 'Approve') {
if (value == 'Decline')
$('#declinediv').show();
else
$('#declinediv').hide();
}
else {
$('#declinediv').hide();
}
});
//////////////////////////
$("#aspnetForm").validate({
rules: {
<%=txtdeclinereason.UniqueID %>: {
minlength: 2,
required: true
}
}, messages: {
<%=txtdeclinereason.UniqueID %>:{
required: "* Required Field *",
minlength: "* Please enter atleast 2 characters *"
}
}, onsubmit: true
});
//////////////////////////////////
$('#btnsubmit').click(function(evt){
var isValid = $("#aspnetForm").valid();
if (!isValid)
{
evt.preventDefault();
}
});
});
function myredirect(v, m, f) {
window.location.href = v;
}
</script>
<table style="border: 1px black solid; text-align: center; vertical-align: middle"
width="100%">
<tr>
<td>
<asp:RadioButtonList ID="rbtnlstapprover" runat="server" RepeatDirection="Horizontal"
CssClass="rblist" DataTextField="username" DataValueField="emailaddress">
<asp:ListItem Text="Approve" Value="Approve" />
<asp:ListItem Text="Decline" Value="Decline" />
</asp:RadioButtonList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="rbtnlstapprover"
Text="*" ErrorMessage="Please select atleast one Approver" ValidationGroup="approvalgroup"
Display="Dynamic" />
</td>
</tr>
<tr>
<td>
<div id="declinediv">
<asp:TextBox ID="txtdeclinereason" runat="server" TextMode="MultiLine" Columns="80"
Rows="5" />
</div>
</td>
</tr>
<tr>
<td>
<asp:Button ID="btnsubmit" runat="server" Text="Submit" CssClass="RegularButton"
CausesValidation="true" ValidationGroup="approvalgroup" OnClick="btnsubmit_Click" />
</td>
</tr>
</table>
如何停止执行后面的代码?谢谢你的帮助。
编辑:
我能够通过为按钮添加 OnClientClick 事件来修复问题
if ($('#declinediv').is(':visible'))
{
var isValid = $("#aspnetForm").valid();
alert(isValid);
if (isValid)
return true;
else
return false;
}
else
{
return true;
}