Validate fields with Onclientclick

Asked

Viewed 436 times

1

I’m trying to call a function Javascript through the OnClientClick.

The problem is that when running in the browser it does not validate the fields, it is as if the function was simply not called.

Javascript:

function VerificaCampos() {
   //verifica processo    
   var ddlprocesso = document.getElementById("<%=ddlProcesso.ClientID%>")
   if (ddlempresa.options[ddlprocesso.selectedIndex].value == ""){
      alert("Favor preencher processo!");
      ddlprocesso.focus();
      return false;

Knob:

<asp:Button ID="btnBuscar" runat="server" CssClass="botao" 
  Text="Gerar" OnClientClick="if(VerificaCampos()) return false;" 
  OnClick="btnBuscar_Click"/>
  • You even put an Alert inside the function to see if it is called?

  • If your role is in a file .js will not work the part of asp.net: <%=ddlProcesso.ClientID%>. You can confirm if you are in a file or on the same page .aspx? Second, as @Caiqueromero commented, validated if you are entering Function, using a alert or console.log?

  • @Robervalvenicio Did it?

1 answer

1


One of the problems is that in your javascript you are instantiating the ddlProcesso and then and then tetando check another object that has not been declared the ddlEmpresa

function VerificaCampos() {
   //verifica processo    
   var ddlprocesso = document.getElementById("<%=ddlProcesso.ClientID%>")
   //if (ddlempresa.options[ddlprocesso.selectedIndex].value == ""){
   if (ddlprocesso.options[ddlprocesso.selectedIndex].value == ""){
      alert("Favor preencher processo!");
      ddlprocesso.focus();
      return false;
    }
}

Later as the colleague commented, if your javascript is in a js file separate from aspx, the Response.Write() will not work, but you can get around it in a simple way. Just put in your dropdown the attribute ClientIDMode="Static" so your DOM id will be "ddlProcesso" too

<asp:DropDownList ID="ddlProcesso" runat="server" ClientIDMode="Static"></asp:DropDownList>

And in javascript you can select it without the help of ASP.Net

var ddlprocesso = document.getElementById("ddlProcesso");

And lastly, change your button event, to OnClientClick="return VerificaCampos();"

<asp:Button ID="btnBuscar" runat="server" CssClass="botao" 
  Text="Gerar" OnClientClick="return VerificaCampos();" OnClick="btnBuscar_Click"/>

Browser other questions tagged

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