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.
05 |
< TD >< INPUT type = "text" value = "" name = "username" title = "Enter Username" />< TD > |
09 |
< TD >< INPUT type = "text" value = "" name = "username" title = "Enter Age" />< TD > |
13 |
< TD >< INPUT type = "text" value = "" name = "username" title = "Enter City" />< TD > |
17 |
< TD >< INPUT type = "text" value = "" name = "username" title = "Enter Comment" />< TD > |
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.
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 (){ |
03 |
this .value = $( this ).attr( 'title' ); |
04 |
$( this ).addClass( 'text-label' ); |
06 |
$( this ).focus( function (){ |
07 |
if ( this .value == $( this ).attr( 'title' )) { |
09 |
$( this ).removeClass( 'text-label' ); |
13 |
$( this ).blur( function (){ |
14 |
if ( this .value == '' ) { |
15 |
this .value = $( this ).attr( 'title' ); |
16 |
$( this ).addClass( 'text-label' ); |
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