2

I am trying to show alert if the input is not valid, but OnClientClick is not working, here is my code:

function validation1() {

    if (document.getElementById('firstname').value == "" || document.getElementById('firstname').value == "First Name..." ){
    alert("Please Enter First Name");
    } 
    if(document.getElementById('lastname').value == "" || document.getElementById('lastname').value == "Last Name..."){
    alert("Please Enter Last Name");
    }
}


<asp:Button runat="server" ID="SearchButton" Text="Instant Search" OnClick="SearchButton_Click" OnClientClick="validation1" />

My code is in master page, so could this be an issue?

Have tried many different ways to call the function using OnClientClick but no success:

halfer
  • 19,824
  • 17
  • 99
  • 186
Wasi
  • 743
  • 4
  • 18
  • 37

2 Answers2

3

You're missing your parenthesis (brackets) from the function call, you might also want the result of the validation function determine if the server side click should fire:

function validation1() {

if (document.getElementById('firstname').value == "" ||document.getElementById('firstname').value == "First Name..." ){
   alert("Please Enter First Name");
   return false;
} 

if(document.getElementById('lastname').value == "" || document.getElementById('lastname').value == "Last Name..."){
   alert("Please Enter Last Name");
   return false;
}

return true;
}

<asp:Button runat="server" ID="SearchButton" Text="Instant Search" OnClick="SearchButton_Click" OnClientClick="return validation1();" />

The main difference here is that the client click function is returning a value to state if the validation passed or not as well as the actual method call declared correctly, easy thing to miss :).

halfer
  • 19,824
  • 17
  • 99
  • 186
Paulie Waulie
  • 1,690
  • 13
  • 23
  • @Wasi - OK, do you have any idea why it's not working? Using a javascript debugger like Firebug/Chrome do you see any script errors? If you put an laert at the top of the validation function, is it called? If so then the code maybe failing at the point of trying to get the element because the id is incorrect. – Paulie Waulie Jan 08 '13 at 13:24
0

Try this

    function validation1() {

    if (document.getElementById('firstname').value == "" || document.getElementById('firstname').value == "First Name..." ){
    alert("Please Enter First Name");
    return false;
    } 
    if(document.getElementById('lastname').value == "" || document.getElementById('lastname').value == "Last Name..."){
    alert("Please Enter Last Name");
    return false;
    }
}

Here is aspx code

<asp:Button runat="server" ID="SearchButton" Text="Instant Search" OnClick="SearchButton_Click" OnClientClick="return validation1();" />
iJade
  • 23,144
  • 56
  • 154
  • 243