Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...