Click here to Skip to main content
15,889,877 members
Articles / jQuery

7 jQuery Code Snippets Every Web Developer Must Have

Rate me:
Please Sign up or sign in to vote.
4.86/5 (5 votes)
4 Sep 2013CPOL2 min read 24.4K   30   9
Here is a list of 7 jQuery code snippets that every web developer must have

jQuery extensively simplified a web developer's life and has become a leader in JavaScript available libraries. There are a lot of useful jQuery snippets available, but here in this post, I am going to share 7 basic and widely used code snippets that every front-end web developer must have. Even those who are new to jQuery can easily understand and benefit from these routinely used code snippets.

1. Print Page Option

Providing option to print a page is a common task for web developers. Following is the available code:

JavaScript
<!-- jQuery: Print Page -->
$('a.printPage').click(function(){
           window.print();
           return false;
}); 
<!-- HTML: Print Page -->
<div>
   <a  class="printPage" href="#">Print</a>
</div>

2. Helping Input Field/Swap Input Field

In order to make an Input Text field helpful, we normally display some default text inside it (For Example "Company Name") and when user clicks on it, text disappears and user can enter the value for it. You can try it yourself by using the following code snippet.

JavaScript
<!-- jQuery: Helping Input Field -->
$('input[type=text]').focus(function(){    
           var $this = $(this);
           var title = $this.attr('title');
           if($this.val() == title)
           {
               $this.val('');
           }
}).blur(function() {
           var $this = $(this);
           var title = $this.attr('title');
           if($this.val() == '')
           {
               $this.val(title);
           }
});
<!-- HTML: Swap Input Field -->
<div>
       <input type="text" 
       name="searchCompanyName" 
       value="Company Name"
       title="Company Name" />
</div>

3. Select/Deselect All Options

Selecting or deselecting all available checkbox options using a link on HTML page is a common task.

JavaScript
<!-- jQuery: Select/Deselect All -->
$('.SelectAll').live('click', function(){
$(this).closest('.divAll').find('input[type=checkbox]').attr('checked', true);
return false; });
$('.DeselectAll').live('click', function(){
$(this).closest('.divAll').find
('input[type=checkbox]').attr('checked', false);
return false; });
<!-- HTML: Select/Deselect All -->
<div class="divAll">  <a href="#" 
class="SelectAll">Select All</a>&nbsp;  
<a href="#" class="DeselectAll">Deselect All</a>  <br />  \
<input type="checkbox" 
id="Lahore" /><label for="Lahore">Lahore</label>  
<input type="checkbox" 
id="Karachi" /><label for="Karachi">Karachi</label>  
<input type="checkbox" 
id="Islamabad" 
/><label for="Islamabad">Islamabad</label> </div>

4. Disabling Right Click

For web developers, it's common to disable right click on certain pages, so the following code will do the job.

JavaScript
<!-- jQuery: Disabling Right Click -->
$(document).bind("contextmenu",function(e){
       e.preventDefault();

   });

5. Identify Which Key is Pressed

Sometimes, we need to validate the input value on a textbox. For example, for "First Name" we might need to avoid numeric values. So, we need to identify which key is pressed and then perform the action accordingly.

JavaScript
<!-- jQuery: Which key is Pressed. -->
$('#txtFirstName').keypress(function(event){
     alert(event.keyCode);
  });
<!-- HTML: Which key is Pressed. -->
<asp:TextBox ID="txtFirstName" 
runat="server"></asp:TextBox>

6. Validating an Email

Validating an email address is a very common task on HTML form.

JavaScript
<!-- jQuery: Validating an email. -->
$('#txtEmail').blur(function(e) {
            var sEmail = $('#txtEmail').val();
            if ($.trim(sEmail).length == 0) {
                alert('Please enter valid email address');
                e.preventDefault();
            }        
            var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]
                             {2,4}|[0-9]{1,3})(\]?)$/;        
            if (filter.test(sEmail)) {
                alert('Valid Email');
            }
            else {
                alert('Invalid Email');
                e.preventDefault();
            }
        });
<!-- HTML: Validating an email-->
<asp:TextBox id="txtEmail" runat="server" />

7. Limiting MaxLength for TextArea

Lastly, it is usual to put a textarea on a form and validate maximum number of characters on it.

JavaScript
<!-- jQuery: Limiting MaLength for TextArea -->
   var MaxLength = 500;
       $('#txtDescription').keypress(function(e)
       {
          if ($(this).val().length >= MaxLength) {
          e.preventDefault();}
       });
<!-- HTML: Limiting MaLength for TextArea-->
<asp:TextBox ID="txtDescription" runat="server"
                         TextMode="MultiLine" Columns="50" 
                         Rows="5"></asp:TextBox>

This is my selection of jQuery code snippets but jQuery is a very powerful client-side framework and a lot more can be done using it.

Other Web Development Articles

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Emaratech
United Arab Emirates United Arab Emirates
Imran Abdul Ghani has more than 10 years of experience in designing/developing enterprise level applications. He is Microsoft Certified Solution Developer for .NET(MCSD.NET) since 2005. You can reach his blogging at WCF Tutorials, Web Development, SharePoint for Dummies.

Comments and Discussions

 
Suggestion.live() has been removed from jQuery Pin
Julian Nicholls9-Sep-13 1:13
Julian Nicholls9-Sep-13 1:13 
BugEmail Address Validation Pin
Hawkeye665-Sep-13 4:19
Hawkeye665-Sep-13 4:19 
GeneralRe: Email Address Validation Pin
Imran Abdul Ghani5-Sep-13 4:25
Imran Abdul Ghani5-Sep-13 4:25 
GeneralRe: Email Address Validation Pin
Imran Abdul Ghani5-Sep-13 5:11
Imran Abdul Ghani5-Sep-13 5:11 
BugRe: Email Address Validation Pin
Hawkeye665-Sep-13 8:14
Hawkeye665-Sep-13 8:14 
GeneralRe: Email Address Validation Pin
Imran Abdul Ghani5-Sep-13 9:42
Imran Abdul Ghani5-Sep-13 9:42 
Questionnon so usefulll Pin
giammin4-Sep-13 22:20
giammin4-Sep-13 22:20 
disable right click... Come on does anybody still try to block this?? you can bypass this in tousands of way

have you ever heard about placeholder attribute? http://www.w3schools.com/tags/att_input_placeholder.asp[^]
GeneralMy vote of 5 Pin
Carsten V2.04-Sep-13 9:13
Carsten V2.04-Sep-13 9:13 
GeneralMy vote of 5 Pin
Mahesh Babu Kudikala4-Sep-13 7:35
Mahesh Babu Kudikala4-Sep-13 7:35 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.