How to call a javascript function from an external file?

Asked

Viewed 2,810 times

2

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

Cannot get value from 'value' property: the object is null or undefined.

This error appears in this function line:

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

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

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

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

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

Email validation function in file . js:

    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;
      }
    }

2 answers

3

Remove the <%= %>.

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

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

Put it that way and it will work:

(document.getElementById("txtEmail").value == "")

1

To call the ID of a component . NET via javascript it is necessary to set the attribute Clientidmode in creating 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 locate it through JS using 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 declaration of the component is 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 you open the page in the browser check through the Elements Inspector of your browser, which ID was generated, if only as ID="txtEmail" then you can access it directly:

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

A great source on how Clientid works: Clientidmode in ASP.NET 4.0

Up until

Browser other questions tagged

You are not signed in. Login or sign up in order to post.