Click here to Skip to main content
15,886,012 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have two textboxes and a button. I want to alert a validation message when first text box is empty. But it is not working. The code is written below.
function validation()
{
    var valfirst= document.getElementById("FirstName").value;
        if(valfirst == null || valfirst == "")
    {
        return false;
    }
    else
    {
       return(valfirst);
    }

}

<html>
  <body>
    <script type="text/javascript" src="External.js">
    </script>
    <form id="frm1" method="get">
      First Name: <input type="textbox" id="FirstName"/>
      Second Name:<input type="textbox" id="SecondName"/>
      <input type="button" value="Submit" onClick="validation()"/>
    </form>
</body>
</html>
Posted
Updated 12-Jan-11 19:01pm
v2

Following is the corrected code:

XML
<html>
  <body>
    <script type="text/javascript">
        function validation() {
            var valfirst = document.getElementById("FirstName").value;
            if (valfirst == null || valfirst == "") {
                alert("FirstName is required");
                return false;
            }
            else {
                return true;
            }
        }
    </script>
    <form id="frm1" method="get">
      First Name: <input type="textbox" id="FirstName"/>
      Second Name:<input type="textbox" id="SecondName"/>
      <input type="submit" value="Submit" onClick="return validation()"/>
    </form>
</body>
</html>


However, I'd recommend to use the Asp.net Validators for validation. See http://quickstarts.asp.net/QuickStartv20/aspnet/doc/validation/default.aspx[^] to learn about this.
 
Share this answer
 
Comments
Hiren solanki 13-Jan-11 1:21am    
Very good answer mate.
Al-Farooque Shubho 13-Jan-11 1:22am    
Thanks mate.
Lyn123 13-Jan-11 1:22am    
T
Hi,

Rewrite the javascript fucntion as follows.
fucntion Validate()
{
C#
var valfirst= document.getElementById("FirstName").value;
       if(valfirst == null || valfirst == "")
   {
       document.getElementById("FirstName").focus();
return false;
   }


C#
var vallast= document.getElementById("LastName").value;
       if(vallast== null || vallast== "")
   {
       document.getElementById("LastName").focus();
return false;
   }




}

Do the HTML page modifications as follows.

XML
<html>
  <body>
    <script type="text/javascript" src="External.js">
    </script>
    <form id="frm1" method="get">
      First Name: <input type="text" id="FirstName"/>
      Second Name:<input type="text" id="SecondName"/>
      <input type="button" value="Submit" onClick="validation()"/>
    </form>
</body>
</html>


Regards,
Kiran
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900