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:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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" />
Method 2
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.
Method 3
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 !
Method 4
//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" />
Method 5
if ($('#<%= yourtextboxname.ClientID %>').val() =="")
// String is not empty
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0