Please navigate to the bottom of the page for Table of Contents

Saturday, July 16, 2011

jQuery to create default text for a textbox

In the previous post we explored how to use jQuery to block paste in a textbox. In this post, let’s see how we can provide some default text (as a hint) to the user.

Question: On many complex sites, there is a search textbox that allows users to search the site for some relevant information. Explain how to provide some helper text to the user. This information should only be displayed if the textbox is not in focus and does not contain user input.

For example, on www.geocaching.com, the home page has this search box with the default text:

image

The solution to this problem is bit more involved than the block paste problem. To solve this, let’s tackle small pieces of the problem and then see the full solution at the end.

First of all, let’s define our basic text box on ASP.NET page:

<asp:TextBox runat="server" ID="searchTb"></asp:TextBox>



We will use the tooltip property to define our default text. In addition, to distinguish the default text from actual user input, let’s put some simple CSS on it. Our textbox now looks like:


<asp:TextBox runat="server" ID="searchTb" 
CssClass="searchText"
ToolTip="Enter keyword to search...">
</asp:TextBox>


Now, let us look at the jQuery counterpart. We will need to attach to the blur() and focus() events of the textbox.


For the blur() event, we we will check if the textbox is empty and if so, we will set the CSS class and default text.


For the focus() event, we will check if the textbox value is the same as the tooptip and if so, we we will remove the CSS class and empty its content.


As the final step, we will call the blur() function when the document is ready.


The complete code looks like:


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DefaultText.aspx.cs" 
Inherits="jQueryInterviewQuestions.DefaultText" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Default Text Example</title>
<!-- include jQuery -->
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
   1:  
   2:  
   3:     <script type="text/javascript">
   4:         // when the document is ready
   5:         $(document).ready(function () 
   6:         {
   7:             // find the search box
   8:             var searchBox = $('#<%=searchTb.ClientID%>');
   9:  
  10:             // define the blur event
  11:             searchBox.blur(
  12:                 function() 
  13:                 {
  14:                     // if the value of the search textbox is empty
  15:                     if (searchBox.val() == "") 
  16:                     {
  17:                         // add the CC class
  18:                         searchBox.addClass("searchText");
  19:                         // and set the default text
  20:                         searchBox.val(this.title);
  21:                     }
  22:                 }
  23:             );
  24:  
  25:             // tap into the focus event
  26:             searchBox.focus(
  27:                 function() 
  28:                 {
  29:                     // on focus, if the text box has the default text
  30:                     if (searchBox.val() == this.title) 
  31:                     {
  32:                         // remove the text and class
  33:                         searchBox.removeClass("searchText");
  34:                         searchBox.val("");
  35:                     }
  36:                 }
  37:            );
  38:  
  39:             // call the blur function
  40:             searchBox.blur();
  41:         });
  42:     
</script>

<!-- define some simple CSS for the searchTB -->
<style type="text/css">
.searchText
{
color:Red;
font-style:italic;
}
</style>
</head>

<body>
<form id="form1" runat="server">
<p></p>
<div align="center">

What are you searching today:
<!-- the search textbox with tooltip and CSS -->
<asp:TextBox runat="server" ID="searchTb" Width="300px"
CssClass="searchText"
ToolTip="Enter keyword to search...">
</asp:TextBox>

<asp:Button runat="server" ID="searchBtn" Text="Search" />
</div>
</form>
</body>
</html>

16 comments:

  1. This can help you http://workwithphp.info/?p=8

    ReplyDelete
    Replies
    1. I am glad that I saw this post. It is informative blog for us and we need this type of blog thanks for share this blog, Keep posting such instructional blogs and I am looking forward for your future posts. Python Projects for Students Data analytics is the study of dissecting crude data so as to make decisions about that data. Data analytics advances and procedures are generally utilized in business ventures to empower associations to settle on progressively Python Training in Chennai educated business choices. In the present worldwide commercial center, it isn't sufficient to assemble data and do the math; you should realize how to apply that data to genuine situations such that will affect conduct. In the program you will initially gain proficiency with the specialized skills, including R and Python dialects most usually utilized in data analytics programming and usage; Python Training in Chennai at that point center around the commonsense application, in view of genuine business issues in a scope of industry segments, for example, wellbeing, promoting and account. Project Center in Chennai

      Delete

  2. The share your really gives us excitement. Thanks for your sharing. If you feel tired at work or study try to participate in our games to bring the most exciting feeling. Thank you!
    hotmail sign in | red ball game | 192.168.1.1

    ReplyDelete
  3. The blog or and best that is extremely useful to keep I can share the ideas of the future as this is really what I was looking for, I am very comfortable and pleased to come here. Thank you very much.
    animal jam | five nights at freddy's | hotmail login

    ReplyDelete
  4. Thank you for sharing your article. Great efforts put it to find the list of articles which is very useful to know, Definitely will share the same to other forums.


    appvn app
    Splitwise app

    ReplyDelete
  5. It was a brilliant opportunity to visit this sort of site and I am cheerful to know, much obliged to you such a great amount for allowing us to have this open door.mobile app development company chennai

    ReplyDelete
  6. I enjoy reading it. I fundamental to learn more on this subject.. Thanks for the sake theme this marvellous post.. Anyway, I am gonna subscribe to your silage and I wish you post again soon. ny web design firms

    ReplyDelete
  7. Top-notch post it is surely. My friend has been awaiting for this content. new york website design company

    ReplyDelete
  8. I really like your writing style, wonderful information, thankyou for posting : D. branding agencies in san francisco

    ReplyDelete
  9. I am glad to be a visitor of this thoroughgoing website ! , appreciate it for this rare info ! . branding firms san francisco

    ReplyDelete
  10. Very informative and fantastic bodily structure of content material , now that’s user friendly (:. san francisco design agency

    ReplyDelete
  11. This is my first time visit to your blog and I am very interested in the articles that you serve. Provide enough knowledge for me. Thank you for sharing useful and don't forget, keep sharing useful info: sms marketing services

    ReplyDelete
  12. The Master's Guide to text message marketing
    A large number of private companies use instant message advertising to empower expanded promoting commitment from possibilities and clients. As far as we can tell, most independent ventures use text showcasing to produce expanded client securing, convey advancements and warnings, augment client support viability, and increment inside productivity.
    From retail organizations and not-for-profit associations to land and eateries, text showcasing is utilized by more independent companies than at any time in recent memory.

    ReplyDelete
  13. Very excellent post!!! Thank you so much for your great content. Keep posting.....

    Apache Spark Training in Pune
    Spark Training Institute in Pune

    ReplyDelete
  14. Texting is an extremely effective communication & marketing channel for tax preparation services. 98% of text messages are read within 3 minutes of receipt! That’s significant when you consider that 90% of emails are considered SPAM so email marketing for tax professionals just isn’t as effective anymore. Whether you are marketing an accounting firm or just tax preparation software

    ReplyDelete
  15. We’re a tax preparation company in textellent in providing tax planning/tax filing, firm registration, and financial services. We are working with Individuals, Businesses, Charities in the world, and offering them professional tax services with their unique tax filing requirements marketing for accountant

    ReplyDelete