0

I am having some problem with OnClientClick.

I added a button into my webform like this.

<asp:Button ID="Button1" runat="server" onclick="Button1_Click" 
        style="top: 307px; left: 187px; position: absolute; height: 26px; width: 90px" 
        Text="Submit" OnClientClick="return validate()" />

And i am writing a javascript inside <head>immediately after the <title>.

<script language="javascript" type="text/javascript">
    function validate() {
        if (document.getElementById("<%=TextBox1%>").value == "") {
        alert("textbox1 should not be empty");
        }
        else if(document.getElementById("<%=TextBox2 %>").value==""){
        alert("textbox2 should not be empty");
        }
                        }
</script>

TextBox1andTextBox2 are the Id's of two textboxes.

But when i click on Submit button, OnClick is firing but OnClientClick is not firing.

Whats the problem ?

Please help.

NoLifeKing
  • 1,909
  • 13
  • 27
Ranadheer Reddy
  • 4,202
  • 12
  • 55
  • 77
  • first thing your javascript code have error so it's not behaving as you are expecting it to do. – Niranjan Singh May 30 '12 at 04:56
  • 1
    Try adding OnClientClick="javascript:return validate();" and also make sure that you have no errors in your script by looking into errors table in error console. – Sudhakar B May 30 '12 at 04:57

4 Answers4

6

When taking the ID from the textboxes, you'll have to use <%=TextBox1.ClientID%> in your javascript.

And you should also return false from the validate-function when an error occurs.

Replace your javascript with:

function validate() {
    if(document.getElementById('<%=TextBox1.ClientID%>').value == '') {
        alert('Textbox1 should not be empty');
        return false;
    }
    if(document.getElementById('<%=TextBox2.ClientID%>').value == '') {
        alert('Textbox2 should not be empty');
        return false;
    }
}
NoLifeKing
  • 1,909
  • 13
  • 27
  • 1
    You can solve this even easier if you use jQuery, then you can use `$('#<%=TextBox1.ClientID%>').val()` instead of `document.getElementById('<%=TextBox1.ClientID%>').value` – NoLifeKing May 30 '12 at 05:00
1

Try this way:-

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

document.getElementById("<%=TextBox2.ClientID%>").value
Siva Charan
  • 17,940
  • 9
  • 60
  • 95
1

The first thing i see, is that you are using "<%=TextBox1%>" without the .ClientID, which is what recognizes the texbox on the client side. naturally, without id, you javascript cannot find the object (and probably throws an exception as well)

Darshana
  • 2,462
  • 6
  • 28
  • 54
YavgenyP
  • 2,113
  • 14
  • 11
1

(document.getElementById("<%=TextBox1%>").value == "")

will render as

(document.getElementById("System.Web.UI.WebControls.TextBox").value == "").

so try to use document.getElementById("<%=TextBox1.ClientID%>").value in the javascript function.

Ryan M
  • 1,721
  • 2
  • 15
  • 22
dotnetmirror.com
  • 293
  • 2
  • 10