프로그램/script

참쉬운 input box 기본 문자 처리....

mulderu 2010. 11. 10. 09:46
jQuery를 이용하면 기존에 삽질을 한방에 정리 해 줄 수 있는 좋은 방법들이 많은것 같다... 이것을 알았을때 기존의 삽질을 생각하면 갑자기 머리가 멍해 진다...

잘 그럼... 여기에 default input box text를 처리 하는데 삽질 하지 않고 간단히 처리 하기 예제가 있다... (원래 위치)


-------------------------------------------------------------------


Let us see how can we use JavaScript/jQuery to achieve this.

Step 1: The HTML

We will use following simple HTML Form. Create an HTML file and Copy and paste following code.

01 <FORM method="post">
02 <TABLE>
03 <TR>
04     <TD>Username</TD>
05     <TD><INPUT type="text" value="" name="username" title="Enter Username"/><TD>
06 </TR>
07 <TR>
08     <TD>Age</TD>
09     <TD><INPUT type="text" value="" name="username" title="Enter Age"/><TD>
10 </TR>
11 <TR>
12     <TD>City</TD>
13     <TD><INPUT type="text" value="" name="username" title="Enter City"/><TD>
14 </TR>
15 <TR>
16     <TD>Comment</TD>
17     <TD><INPUT type="text" value="" name="username" title="Enter Comment"/><TD>
18 </TR>
19 </TABLE>
20 </FORM>

Notice that while defining each text fields, we have provided title attribute. The text that is displayed on background of textbox is taken from the Title attribute. So generally the title attribute should be like “Enter Email Address” or “Type Address”.

Step 2: The CSS

Copy following CSS in your HTML file. You may want to include a separate CSS file for this.

1 .text-label {
2     color: #cdcdcd;
3     font-weight: bold;
4 }

The above CSS class is applied to the Textbox when user has not entered anything in it. Once the user starts typing in Textbox the CSS class is removed.

Step 3: The JavaScript

We are almost done with our implementation. Only thing left is the JavaScript code that actually add and remove css to textboxes.

01 $('input[type="text"]').each(function(){
02   
03     this.value = $(this).attr('title');
04     $(this).addClass('text-label');
05   
06     $(this).focus(function(){
07         if(this.value == $(this).attr('title')) {
08             this.value = '';
09             $(this).removeClass('text-label');
10         }
11     });
12   
13     $(this).blur(function(){
14         if(this.value == '') {
15             this.value = $(this).attr('title');
16             $(this).addClass('text-label');
17         }
18     });
19 });

The above code is straight forward. For each textbox in the webpage, we hook handler function to events focus and blur. When Textbox is focused, check if the value is same as Title. If so, then remove the background label css and let user edit the value in textbox. And while blur event(focus lost), check the value: if user has not entered anything, set the background css again.

Online Demo


Online Demo