How to call a javascript function from an external file?

2

I'm having trouble validating a field by clicking the incluir button, so I click on incluir gives this error below:

  

Unable to get 'value' property value: object is   null or undefined.

This error appears in this line of the function:

(document.getElementById("<%=txtEmail.ClientID%>").value == "")

The file containing the function has already been instantiated in the html code:

<script src="Javascript/validacao.js" type = "text/javascript" > < /script>

Code view where it contains incluir_click and its Page_Load returning the js function:

Protected Sub Page_Load(sender As Object, e As EventArgs)
    btnIncluir.Attributes.Add("onclick", "return valida_campos()")
End Sub

E-mail validation function in .js file:

    function valida_campos() {

      if (document.getElementById("<%=txtEmail.ClientID%>").value == "") {
        alert("Email obrigatório");
        document.getElementById("<%=txtEmail.ClientID%>").focus();
        return false;
      }

      var emailPat = /^(\".*\"|[0-9-A-Za-z]\w*)@(\[\d{1,3}(\.\d{1,3}){3}]|[A-Za-z]\w*(\.[A-Za-z]\w*)+)$/;
      var emailid = document.getElementById("<%=txtEmail.ClientID%>").value;
      var matchArray = emailid.match(emailPat);
      if (matchArray == null) {
        alert("O Email esta no formato incorreto. Tente novamente.");
        document.getElementById("<%=txtEmail.ClientID%>").focus();
        return false;
      }
    }
    
asked by anonymous 09.12.2014 / 14:20

2 answers

3

Remove% with%.

The <%= %> takes elements that are from the Server.

If your Javascript function was right on the page it would work.

Put it this way and it will work:

(document.getElementById("txtEmail").value == "")
    
09.01.2015 / 19:31
1

To call the .NET component ID via javascript it is necessary to set the ClientIDMode attribute in the creation of the component to "Static":

<asp:TextBox runat="server" ID="txtNmBanco" Width="140px" MaxLength="80" ClientIDMode="Static" TabIndex="2"  placeholder="Nome do Banco" class="form-control"></asp:TextBox>

This way you can find it through JS using the direct ID:

document.getElementById('txtNumBanco');

However, the way you did it should also work, I have a code that validates email typed as follows:

var txtEmail = document.getElementById('<%= Email.ClientID %>');

And the component declaration looks like this:

 <asp:TextBox ID="Email" runat="server" Width="250px" MaxLength="100" TabIndex="6" onblur="javascript: return ValidaEmail();"
                        ToolTip="Escreva um email que você use com frequência"></asp:TextBox>

When opening the page in the browser, check through the Element Inspector of your browser, which ID was generated, if it is only as ID="txtEmail" then you can access direct:

var valor = document.getElementById("txtEmail").value;

A great source for how ClientID works: ClientIDMode in ASP. NET 4.0

To

    
17.01.2016 / 16:59