How to hide a div (on the client) the client-side check failed?

I am creating an asp.net page with asp.net validation elements. If the validation fails, I want to show the div (on the client). Where can i do this? I cannot find a way to access the OnValidate event on the client. I can do it on the server, but I would rather do it on the client.

+3
source share
3 answers

Use the ASP.NET custom validator .

If for some reason you cannot / do not want to do this, use the ClientScriptManager.RegisterOnSubmitStatement method, and provide a return false on the client side of the script if everything you check fails.

0
source

You can either call the JavaScript function from the code server, using Page.RegisterClientScriptBlock method] 1

as

String scriptString = "<script type='text/javascript'>MakeDivVisible();</script>";
this.RegisterClientScriptBlock("clientScript", scriptString);

and then in the javascript function you can change the display of the div to be blocked, for example

document.getElementById("divId").style.display = 'block';

or if you specify the div attribute runat = "server", you can access the div from the server side code and change its display to block

divId.Style["display"] = "block";
0
source

You want to check on the client and on the server, since you cannot guarantee that the client has JavaScript enabled. Below are the steps for doing this on the client side, as server-side implementation of this should be trivial.

For a simple div, for example:

<div id="divErrors" runat="server" style="display: none;">
    This should only appear when validation fails.
</div>

Add the following JavaScript to your page:

<script language="javascript" type="text/javascript">
    function showErrors() {
        if (!Page_IsValid) {
            document.getElementById('divErrors').style.display = 'block';
        } else {
            document.getElementById('divErrors').style.display = 'none';
        }
    }
</script>

Finally, register a submit script that calls this new showErrors function (in the Page_Load event):

If Not Page.IsPostBack() Then
    Dim scriptName As String = "OnSubmitScript"
    Dim scriptType As Type = Me.GetType()
    Dim script As ClientScriptManager = Page.ClientScript
    If Not script.IsOnSubmitStatementRegistered(scriptType, scriptName) Then
        script.RegisterOnSubmitStatement(scriptType, _ 
                        scriptName, "showErrors();")
    End If
End If
0
source

Source: https://habr.com/ru/post/1729071/


All Articles