Validate fields with OnClientClick

1

I'm trying to call a JavaScript function through 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;

Button:

<asp:Button ID="btnBuscar" runat="server" CssClass="botao" 
  Text="Gerar" OnClientClick="if(VerificaCampos()) return false;" 
  OnClick="btnBuscar_Click"/>
    
asked by anonymous 18.04.2018 / 14:56

1 answer

2

One of the problems is that in your javascript you are instantiating the ddlProcesso and after and after checking another object that has not been declared 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;
    }
}

Then as your colleague commented, if your javascript is in a js file separate from aspx, Response.Write() will not work, but you can work around this in a simple way. Just put in your dropdown the ClientIDMode="Static" attribute so your id in the DOM 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 finally, change the event of your button to OnClientClick="return VerificaCampos();"

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