Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
625 views
in Technique[技术] by (71.8m points)

.net - How to make a Textbox required IF a Checkbox is checked

How can I make a textbox required if a checkbox is checked?

I figure I could write a custom validator, but I was hoping to avoid a full post back to check the validation if possible... I was thinking AJAX had something built in for this scenario, but I've been unable to find it. I'm thinking straight JavaScript would also be a solution, but I could use a head start if that's the best approach.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The JavaScript to handle this isn't very difficult.

Given the following ASP controls:

<asp:TextBox ID="txtSubject" runat="server" />
<asp:CheckBox ID="chkSubjectRequired" runat="server" OnClick="updateValidator();" />
<asp:RequiredFieldValidator ID="rfvSubject" ControlToValidate="txtSubject" ErrorMessage="You must enter a subject." runat="server" />

Add the following JavaScript function:

<script language="javascript" type="text/javascript">
    function updateValidator() {
        var enableValidator = !event.srcElement.status;
        var rfvSubject = document.getElementById('rfvSubject');
        ValidatorEnable(rfvSubject, enableValidator);
    }
</script>

That's all there is to it. You will also want to add the following code to your Page Load event, so that if the user has JavaScript disabled, your required field validator is still turned on or off properly:

rfvSubject.Enabled = chkSubjectRequired.Checked

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...