How to check if a asp text box is empty or not [duplicate]

Possible Duplicate:
textbox empty check using javascript

I have a asp.net button and a asp.net textbox, when I click on button, I want to check if textbox is empty or not but not sure how I can do that,

<div>
    <asp:TextBox ID="txtEU" runat="server"></asp:TextBox>
</div>
<div>
    <asp:ImageButton ID="button" runat="server" OnClientClick="MyFunction(); return false;" ImageUrl="/myfolder/abc.png" />
</div>

in my JavaScript I am doing,

   <script type="text/javascript">
    function doWork() 
    {  
        if($input[]

not sure how to check if its empty or not, if its empty then I am doing something if not then it should call a code behind method for that button.

Answers:

Answer

Read on the ClientIDMode property to see how element ID are generated in ASP.NET (4.0 and above)

function doWork() 
{  
     var textbox = document.getElementById('<%=txtEU.ClientID%>');

     if(textbox.value.length == 0)
     {

     }
}

OR

if(textbox.value == "")

Using Validators will help you handle some of this validation out of the box. One of them is RequiredValidator, which evaluates the value of an input control to ensure that the user enters a value.

<asp:RequiredFieldValidator runat="server" ID="txtEURequiredValidator" ErrorMessage="EU should not be empty" />
Answer

you have the ability to use a RequiredFieldValidator or a CustomValidator if you need to execute a more complex scenario.

Here is a good starting point i think: http://asp.net-tutorials.com/validation/introduction/ (check the links on the right side to have a detailed view of the validators)

Hope this helps.

Answer

You can do like so:

if ($('#<%= txtEU.ClientID %>').val()({
   // String is not empty
}

Explanation:

  • Because, by default, asp.net mangles the html ID for the text box, you will need to inject the name into your jQuery.
  • In jQuery, null and empty can both be tested for with !
Answer
 //javascript code
function Myfunction()
    {   
       if(document .getElementById("<%=txtEU.ClientID %>").value=="")
        {
            alert("Please Enter Text");
           txtEU.focus();
            return false;
        }

        return true;
    }
      //aspcode
 <asp:ImageButton ID="button" runat="server" OnClientClick="return Myfunction();" ImageUrl="/myfolder/abc.png" />
Answer
if ($('#<%= yourtextboxname.ClientID %>').val() =="")
  // String is not empty
}

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.