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>

48 comments:

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

    ReplyDelete
  2. 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
  3. 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
  4. Top-notch post it is surely. My friend has been awaiting for this content. new york website design company

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

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

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

    ReplyDelete
  8. 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
  9. TAXPRO is a chief expert administration firm enhancing the matter of its customers for over 30 decades. We do this by giving a wide array of administrations in the monetary space which ranges from Entry Level Strategy, Taxation consultancy administrations, GST, Audit and Assurance, Accounting, Corporate Compliance, Payroll Services, ESI/PF Consultancy, and part more. We are a group of expense experts that incorporates Chartered Accountants, Advocates, Company Secretaries, Financial counselors offering taxpro to the makers, Traders, Dealers, and specialist organizations of the business. Our administrations are looked for different business, lawful, and tax assessment confusions.

    ReplyDelete
  10. I really like the new design. It is a lot easier to use and visually attractive. 먹튀

    ReplyDelete
  11. i experience so fortunate because i've a blogger such as you that gives fresh ideas depending at the every day scenario. To be very honest, your blogs are easy to examine and apprehend. Desirable success along with your destiny articles as well. thank you for this engaging article. On occasion you operate actual-existence examples on your articles which can be best for me as a reader, but lamentably, from time to time i didn’t get your point inside the put up. It seems fake or irrelevant. Nicely, it’s a very good one. Top notch put up i need to say and thanks for the statistics. Education is truely a sticky concern. But, continues to be many of the leading subjects of our time. I respect your post and sit up for more. I truely cherished reading your blog. It changed into very well authored and smooth to apprehend. Not like other blogs i've examine which can be sincerely no longer that right. Thanks alot! In case you once in a while plan on the use of the web browser that’s now not an problem, however if you’re making plans to browse the internet alot out of your pmp then the ipod’s large screen and better browser can be important. I assume this is a really precise article. You are making this facts thrilling and engaging. You give readers a lot to reflect onconsideration on and i respect that kind of writing. Excellent factors you wrote here.. Fantastic stuff... I think you've made a few actually thrilling factors. Preserve up the good paintings 먹튀검증

    ReplyDelete
  12. thank you because you have got been inclined to share facts with us. We are able to usually recognize all you've got done right here due to the fact i realize you are very concerned with our . I like your put up. It is good to peer you verbalize from the heart and readability in this crucial subject may be effortlessly found.. I study numerous stuff and i found that the manner of writing to clearifing that precisely need to say became excellent so i am inspired and ilike to come back once more in future.. Very beneficial publish. This is my first time i visit here. I found so many thrilling stuff for your weblog especially its dialogue. Actually its remarkable article. Preserve it up. Thank you for the great proportion. Your article has proved your tough work and revel in you've got were given on this discipline. Extremely good . I like it analyzing. Thank you due to the fact you've got been inclined to share information with us. We will always recognize all you have got completed here because i realize you're very worried with our. I'm so extremely joyful i located your blog, i truely located you by means of mistake, even as i used to be watching on google for something else, in any case i am here now and will much like to mention thank for a super put up and a all round entertaining website. Please do maintain up the awesome work. I just stumbled upon your blog and desired to say that i've certainly loved analyzing your blog posts. Any manner i will be subscribing for your feed and i hope you post again soon. High quality website online, in which did u come up with the records on this posting? I have study a few of the articles in your website now, and i definitely like your fashion. Thanks 1,000,000 and please keep up the effective paintings. This is this kind of amazing resource which you are presenting and also you deliver it away at no cost. I like seeing blog that understand the value of imparting a excellent aid free of charge. Changed into studying a number of your content in this internet site and i conceive this net web site is without a doubt informative ! Maintain on putting up. What a fantabulous put up this has been. By no means seen this type of useful submit. I am thankful to you and assume more number of posts like those. Thank you very a great deal. i have genuinely loved studying your weblog posts. Any way i'll be subscribing to your feed and that i hope you put up again quickly. Large thanks for the useful information. What a superb put up i've stumble upon and agree with me i have been looking for for this similar sort of post for past per week and hardly got here across this. Thanks very much and will search for extra postings from you. Thanks for taking the time to put up such treasured data. I latterly came throughout your article and have been analyzing along. I want to explicit my admiration of your writing talent and potential to make readers study from the start to the stop. I would love to study more recent posts and to proportion my thoughts with you. You have got a real potential for writing precise content. I love how you watched and the manner you constitute your perspectives in this text. I trust your way of thinking. Thank you for sharing. I've been waited for goodbye. I can want this publish to general my project inside the college, and it has specific equal subject matter together together with your write-up. Thanks, exact percentage . 메이저사이트

    ReplyDelete
  13. thank you for this notable publish, i discover it very interesting and thoroughly idea out and prepare. I sit up for studying your work within the future. This is my first go to to your net magazine! We are a group of volunteers and new activities inside the same uniqueness. Website gave us helpful facts to paintings. Thanks for the blog loaded with so many information. Stopping by means of your weblog helped me to get what i was seeking out. Exceptional website! I am keen on how it is easy on my eyes it is. Thanks for assisting human beings get the statistics they need. Extraordinary stuff as traditional. Maintain up the terrific paintings!!! I examine your blog publish and this is quality blog publish.. Thanks for taking the time to percentage with us. Have a nice day . The writer has impressed me with the good excellent paintings right here. I'll make certain that i percentage this text with as many people as i will. I suppose it's critical to elevate recognition about this subject. The simplest manner to accomplish that is by sharing. Unheard of weblog. I enjoyed investigating your articles. This is to a high-quality degree an superb investigated for me. I've bookmarked it and i am suspecting examining new articles. Maintain doing stunning! Admiring the time and effort you positioned into your blog and designated facts you offer! The web web page is lovingly serviced and stored as plenty as date. So it should be, thank you for sharing this with us. I’ve been attempting to find some decent stuff at the situation and haven't had any good fortune up until this point, you simply were given a brand new largest fan! I discovered your this put up even as attempting to find a few related records on blog seek... Its an excellent post.. Preserve posting and replace the statistics . This is a amazing article and extremely good examine for me. It's my first visit in your blog, and i have discovered it so beneficial and informative particularly this . I read your blog submit and this is great blog put up.. Thanks for taking the time to percentage with us. Have a pleasant day . The web website is lovingly serviced and saved as a lot as date. So it need to be, thank you for sharing this with us 먹튀검증

    ReplyDelete
  14. howdy there, i suppose your website can be having internet browser compatibility issues. Every time i test your blog in safari, it appears exceptional however, while opening in net explorer, it has some overlapping troubles. I virtually wanted to provide you with a quick heads up! Aside from that, high-quality website! Spot on with this write-up, i definitely experience this website desires lots extra attention. I’ll possibly be returning to examine thru more, thank you for the records! Right day! I may want to have sworn i’ve visited this net website online earlier than but after browsing via a few of the posts i realized it’s new to me. Anyhow, i’m honestly happy i discovered it and i’ll be e book-marking it and checking lower back frequently! 먹튀폴리스주소

    ReplyDelete
  15. having study this i idea it become extremely enlightening. I admire you spending a few time and effort to position this brief article collectively. I over again locate myself for my part spending loads of time both reading and posting feedback. However so what, it was nonetheless worth it! Whats up! This weblog put up couldnot be written any higher! Going via this publish jogs my memory of my previous roommate! He usually saved preaching approximately this. I’ll ship this text to him. Quite sure he’ll have a top notch examine. Many thank you for sharing! I ought to thanks for the efforts you’ve put in scripting this website. I genuinely desire to look the same high-grade content material by you within the future as well. In fact, your innovative writing capabilities has encouraged me to get my very own website now 😉 실시간바카라

    ReplyDelete
  16. thanks for the realistic critique. Me and my neighbor have been just making ready to perform a little studies approximately this. We got a clutch a ebook from our region library however i assume i found out more from this submit. I’m very happy to look such superb information being shared freely accessible.. I do accept as true with this is an great blog. I stumbled upon it on yahoo , i can come again once more. Cash and freedom is the excellent way to change, can also you be wealthy and help other people. 메이저놀이터

    ReplyDelete
  17. appealing phase of content. I just stumbled upon your internet site and in accession capital to assert that i acquire in fact loved account your blog posts. Anyway i can be subscribing to your feeds or even i success you get entry to constantly rapidly. Thanks, i've lately been attempting to find facts about this issue for some time and yours is the greatest i've found until now. However, what regarding the conclusion? Are you advantageous regarding the source? 메이저사이트

    ReplyDelete
  18. that is the first rate attitude, nevertheless is just not assist to make each sence in any way preaching approximately that mather. Certainly any method many thanks in addition to i had undertaking to promote your personal article in to delicius nevertheless it's far seemingly a predicament the usage of your statistics websites can you please recheck the idea. Thanks all over again . Superb blog! I would really like to thank for the efforts you have made in scripting this submit. I am hoping the equal excellent paintings from you in the future as properly. I wanted to thank you for this websites! Thanks for sharing. Exquisite web sites 사설토토

    ReplyDelete
  19. thanks so much for the put up you do. I really like your submit and all you share with us is up to date and pretty informative, i would like to bookmark the page so i'm able to come right here once more to examine you, as you've got achieved a super process. Exciting topic for a blog. I have been looking the net for fun and came upon your internet site. Splendid submit. Thank you a ton for sharing your understanding! It's miles wonderful to peer that a few human beings still installed an effort into coping with their websites. I’ll make certain to check lower back again real soon. Thanks for a very interesting weblog. What else may additionally i am getting that kind of info written in any such ideal method? I’ve a challenge that i'm in reality now running on, and i've been at the look out for such info. This is a splendid inspiring article. I'm pretty a whole lot pleased along with your accurate paintings. You put certainly very beneficial information . Your weblog provided us with valuable statistics to work with. Each & each tips of your publish are outstanding. Thank you a lot for sharing. Hold running a blog 엔포커머니상

    ReplyDelete
  20. Thanks for the exceptional proportion. Your article has proved your hard work and experience you've got were given on this discipline. First rate . I like it studying. I’m certain i'm able to at closing make a move the use of your guidelines on those things i ought to by no means had been capable of touch by myself. You had been so modern to let me be one of these to gain out of your useful statistics. Please understand how a lot i'm thankful. In reality respectable submit. I simply located your blog and wished to mention that i have certainly cherished surfing around your weblog entries. Regardless i'll be subscribing for your nourish and i accept as true with you compose afresh soon! I'm in reality taking part in reading your properly written articles. It seems like you spend a whole lot of time and effort in your weblog. I've bookmarked it and i'm searching forward to studying new articles. That is extraordinarily exciting substance! I've absolutely favored perusing your focuses and feature arrived at the realization which you are ideal approximately a widespread lot of them. You're excellent. I am thrilled and lucky to return on in your web page, i truly preferred the top notch article in your web page. Thanks for this useful data. I additionally determined very thrilling statistics 먹튀검증

    ReplyDelete
  21. this turned into surely an thrilling topic and i kinda consider what you have got referred to right here! Hi there, i have browsed most of your posts. This post might be wherein i were given the most beneficial statistics for my studies. Thanks for posting, perhaps we will see more in this. Are you privy to some other web sites in this issue . Thanks for your posting. Another point is that just being a photographer will involve not only issues in catching award-winning photographs but additionally hardships in acquiring the best digital camera suited to your needs and most especially struggles in maintaining the standard of your camera. This is very real and apparent for those professional photographers that are into capturing a nature's fascinating scenes : the mountains, the particular forests, the actual wild or seas. Going to these daring places absolutely requires a dslr camera that can surpass the wild's unpleasant area. 안전공원

    ReplyDelete
  22. I would like to say that this blog really convinced me to do it! Thanks, very good post 먹튀검증

    ReplyDelete
  23. The links and resources posted by you in the blog are very useful for me! I was looking for this exact and particular information for a long time. Thanks. 안전놀이터

    ReplyDelete
  24. I feel a lot more people need to read this, very good info! 토토검증

    ReplyDelete
  25. Have you ever thought about including a little bit more than just your articles? I mean, what you say is fundamental and all. However just imagine if you added some great visuals or videos to give your posts more, “pop”! Your content is excellent but with pics and clips, this blog could certainly be one of the most beneficial in its niche. Superb blog! Hey! I know this is somewhat off topic but I was wondering which blog platform are you using for this website? I’m getting tired of WordPress because I’ve had problems with hackers and I’m looking at options for another platform. I would be great if you could point me in the direction of a good platform. 먹튀검증

    ReplyDelete
  26. Greetings! This is my 1st comment here so I just wanted to give a quick shout out and tell you I genuinely enjoy reading through your posts. Can you recommend any other blogs/websites/forums that go over the same subjects? Thanks for your time! I like your writing so much! share we be in contact more approximately your post on AOL? I require an expert in this house to unravel my problem. May be that’s you! Having a look forward to look you. Thank you for any other magnificent article. Where else could anyone get that type of information in such a perfect means of writing? I have a presentation subsequent week, and I am at the search for such information. 안전놀이터

    ReplyDelete
  27. This is such a great resource that you are providing and you give it away for free. I love seeing blog that understand the value. Im glad to have found this post as its such an interesting one! I am always on the lookout for quality posts and articles so i suppose im lucky to have found this! I hope you will be adding more in the future.. I really like your post, I always like to read quality content having accurate information regarding the subject. Thanks for sharing. It is such a very amazing post. 안전놀이터

    ReplyDelete
  28. Hi, Neat post. There’s a problem with your web site in internet explorer, would test this… IE still is the market leader and a good portion of people will miss your great writing due to this problem. Spot on with this write-up, I actually assume this website needs far more consideration. I’ll probably be again to read rather more, thanks for that info. When I initially commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get several e-mails with the same comment. Is there any way you can remove people from that service? Bless you! 먹튀검증센터

    ReplyDelete
  29. Its such as you learn my thoughts! You seem to grasp a lot about this, such as you wrote the book in it or something. I believe that you can do with a few percent to power the message house a bit, but other than that, that is excellent blog. A great read. I will certainly be back. Howdy! Would you mind if I share your blog with my facebook group? There’s a lot of people that I think would really appreciate your content. Please let me know. Thanks Great post. I was checking continuously this blog and I am impressed! Very helpful info specifically the last part �� I care for such information a lot. I was seeking this particular info for a long time. Thank you and best of luck. 토토사이트

    ReplyDelete
  30. I’m not sure where you are getting your info, but
    great topic. I needs to spend some time learning much more or
    understanding more. Thanks for fantastic information I was
    looking for this info for my mission.
    바카라사이트


    >cc

    ReplyDelete
  31. Website development demands huge quantity of talent and expertise and only the professional website developer can provide you the ideal website development services. To begin with, you should know what kind of web solutions you're searching for. For instance, if you have hired for web development or web designing of the site, then, the critical facet that has to be is relevance. os path join

    ReplyDelete
  32. I’ve been absent for a while, but now I remember why I used to love this website. Thank you, I will try and check back more often. How frequently you update your site?

    건전마사지

    ReplyDelete
  33. It's the same topic , but I was quite surprised to see the opinions I didn't think of. My blog also has articles on these topics, so I look forward to your visit.오공슬롯


    ReplyDelete
  34. I read the article, this is awesome. Keep updating interesting articles. I am offering statistics assignment help, economics assignment help and finance assignment help to students over the globe at very affordable prices . Superb article. a debt of gratitude is in order for assembling this! This is clearly one extraordinary post. Much obliged for the important data and bits of knowledge you have so given here. This could be one of the most useful blogs we have ever come across on thesubject. Actually excellent info! I’m also an expert in this topic so I can understand your effort. I can give you the address Here you will learn how to do it correctly. Read and write something good. 먹튀마루

    ReplyDelete
  35. This is an incredibly great article. Thank you for explaining these details in detail. ทางเข้าเล่น 123BET

    ReplyDelete
  36. The stuff in this blog is in not only incredible but also providing the great knowledge to the people.
    interactive design agency

    ReplyDelete
  37. I am very happy to discover your post as it will become on top in my collection of favorite blogs to visit 토토커뮤니티

    ReplyDelete
  38. Acknowledges for paper such a beneficial composition, I stumbled beside your blog besides decipher a limited announce. I want your technique of inscription. 토토사이트

    ReplyDelete
  39. Cool stuff you have got and you keep update all of us 먹튀사이트

    ReplyDelete
  40. Cool stuff you have and you keep overhaul every one of us 사설토토

    ReplyDelete
  41. Although sports betting is legal and allowed in many states, there are some risks. It is best to use money you can afford to lose when placing wagers on sports. There are other benefits of sports betting. Here are some. It’s never too late to place bets. You shouldn’t place bets that are too big or you could lose a lot of your money. For those who have almost any inquiries concerning where by and how you can make use of 꽁머니, you possibly can email us from our own page.

    ReplyDelete