Quantcast xữ lý blur và focus events sử dụng jquery

xữ lý blur và focus events sử dụng jquery

by Neon Quach 19. January 2011 05:06

Trong thức tế chúng ta sẽ phải gặp rất nhiều công việc liên quan đến việc xữ lý các sự kiện như: focus, blur (loose focus).... Vấn đề đó rất dễ dàng với Jquery, cho rằng bạn có 2 textboxes user và password, khi page được render xong, thay vì mình thêm 1 dòng message yêu cầu nhập vào user chẳng hạn, mình sẽ put message yêu cầu này ngay trong textbox của username.

Khi user focus vào textbox username thì đoạn text ở đây là --- Please input --- sẽ biến mất, nếu người dùng nhập giá trị vào thì giá trị đó sẽ được thay thế cho --- Please input ---. Còn nếu họ và không nhập giá trị gì, sau đó chuyển sang textbox khác thì message --- Please input --- vẫn còn.

Để giải quết vấn đề trên chúng ta xữ lý sự kiện focus và blur cho textbox (input) sau khi get được giá trị của input đó.

    <div>
        <p>
            <label for="name">
                User name:
            </label>
            <asp:TextBox runat="server" ID="name" />
        </p>
        <p>
            <label for="email">
                Email Address:</label>
            <asp:TextBox runat="server" ID="email" />
        </p>
    </div>

Include jquery vào asp.net page

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js" type="text/javascript"
    language="javascript"></script>


Ở đây mình sẽ handle cho input name, tương tự với input password

<script type="text/javascript">
    $(document).ready(function () {
        $('#name').val('--- Please input ---');
    
    $('#name').blur(function () {
     
       if ($('#name').val() == '')
                $('#name').val('--- Please input ---');
        });
   
     $('#name').focus(function () {
     
       $('#name').val('');
        });
    });
</script>


Checkout source code at:
https://code2code.googlecode.com/svn/trunk/FocusvsLooseFocusUsingJquery

Tags: , ,


Categories: asp.net | javascript | jquery

blog comments powered by Disqus

About me

I'm  currently employed as Software developer at devinition.com and also a Microsoft Certified Technology Specialist (MCTS), Microsoft Certified Professional Developer (MCPD) in Net Framework 2.0 and 3.5: Web Applications and MCTS .NET Framework 3.5, ADO.NET Applications

Powered by BlogEngine.NET 2.5.0.5 - Eco Theme by n3o Web Designers