codeofaninja
website

Two Example Usage of jQuery On() Method

Photo of Mike Dalisay
Modified Friday, March 15, 2013
by - @ninjazhai
How are you guys? Many friends asks me what is the use of jQuery on() method, where and when can we use it and why is it important. So in this tutorial, I'm going to give you two example situations where we can use the jQuery on() method.

Loading and submitting a from without page refresh. Click to enlarge.

By definition, jQuery on() method attaches an event handler function (click, submit, etc.) to one or more elements (div, p, etc.). In my experience, I used jQuery on() when:

  • I want to load a new HTML form on a DIV and submit it without page refresh.
  • I want to reload a list of records and use the actions like 'Delete'.
By the way, you can download all the codes used in this post:

Loading Different Forms to a DIV

This code can load the 'Add User' and 'Add Role' form to the 'formContainer' DIV (one at a time). Our goal is to submit the form without page refresh. To achieve that we are going to use the on() method. See the live demo:

load and submit form with on() - jQuery On() Tutorial - live demo

form_w_on.php code:

<html>
    <head>
        <title>jQuery On() Tutorial - submit with on()</title>
    
        <style>
        #addNewUser, #addNewRole{
            cursor:pointer;
            float:left;
            text-decoration:underline;
        }
        
        #formContainer{
            border:thin solid #000;
            padding:0.5em;
            margin:1em 0 0 0;
        }
        
        .clearBoth{
            clear:both;
        }
        </style>
        
    </head>
<body>

<div id='addNewUser'>[+ New User]</div>
<div id='addNewRole'>[+ New Roles]</div>

<div class='clearBoth'></div>

<div id='formContainer'>
    <!--here is where the form will be loaded -->
</div>

<script src='js/jquery-1.9.1.min.js'></script>
<script>
$(document).ready(function(){

    // when user clicks '[+ New User]', it will load the add_user.php file
    $('#addNewUser').click(function(){
        
        $('#formContainer').load('add_user.php', function(){
            console.log('user form loaded!');
        });
        
    });
    
    // when user clicks '[+ New Roles]', it will load the add_role.php file
    $('#addNewRole').click(function(){
        $('#formContainer').load('add_role.php', function(){
            console.log('role form loaded!');
        });
    });
    
    // when the user submits the 'add new user' form
    $(document).on('submit', '#addUserForm', function(){ 
        alert('Add new user form is submitted!');
        return false;
    });

    // when the user submits the 'add new role' form
    $(document).on('submit', '#addRoleForm', function(){ 
        alert('Add new role form is submitted!');
        return false;
    });
    
    
});
</script>

</body>
</html>

add_user.php code:
<form id='addUserForm'>
    <div>Firstname: <input type='text' name='firstname' /></div>
    <div>Lastname: <input type='text' name='lastname' /></div>
    <div><input type='submit' value='Save' /></div>
</form>

add_role.php code:
<form id='addRoleForm'>
    <div>User Role: <input type='text' name='role' /></div>
    <div>Description: <input type='text' name='description' /></div>
    <div><input type='submit' value='Save' /></div>
</form>

Without the on() method, jQuery code usually looks like this (form_w_out_on.php):
<script>
$(document).ready(function(){

    // when user clicks '[+ New User]', it will load the add_user.php file
    $('#addNewUser').click(function(){
        
        $('#formContainer').load('add_user.php', function(){
            console.log('user form loaded!');
        });
        
    });
    
    // when user clicks '[+ New Roles]', it will load the add_role.php file
    $('#addNewRole').click(function(){
        $('#formContainer').load('add_role.php', function(){
            console.log('role form loaded!');
        });
    });
    
    // when the user submits the 'add new user' form
    $('#addUserForm').submit(function() {
        alert('Add user form is submitted!');
        return false;
    });

    // when the user submits the 'add new role' form
    $('#addRoleForm').submit(function() {
        alert('Add new role form is submitted!');
        return false;
    });
    
});
</script>
Here's a live demo without using the on() method, it reloads the whole page.

load and submit form without on() - jQuery On() Tutorial - live demo


Loading Table List to a DIV

jquery on() tutorial - Loading Table List to a DIV

In this example, when the user clicks on the "[Load List]" text, it will load a table list of data (list.php) with a 'Delete' action right across each records.

Loading Table List to a DIV - jQuery on() tutorial

index.php code:

<html>
    <head>
        <title>jQuery on() tutorial - loading lists</title>
        
        <style>
        #myTable{
            float:left;
            margin:1em 0 0 0;
        }
        
        #myTable th, 
        #myTable td{
            border:thin solid #000;
            padding:1em;
        }
        
        .deleteAction{
            cursor:pointer;
        }
        
        #loadAction{
            cursor:pointer;
            text-decoration:underline;
        }
        </style>
        
    </head>
<body>

<div id='loadAction'>[Load List]</div>

<div id='listContainer'>
    <!--here is where the form will be loaded -->
</div>

<script src='js/jquery-1.9.1.min.js'></script>
<script>
$(document).ready(function(){

    $('#loadAction').click(function(){
        
        $('#listContainer').load('list.php', function(){
            console.log('list loaded!');
        });
        
    });
    
    /*
    // using this code won't pop up 'Are you sure?'
    $('.deleteAction').click(function(){
        if(confirm('Are you sure?'){
             // do things if ok
        }
    });
    */
    
    $(document).on('click', '.deleteAction', function(){ 
        if(confirm('Are you sure?')){
             // do things if ok
        }
    });
    
});
</script>


</body>
</html>

Similarly, as indicated in the code comments, 'Are you sure?' alert dialog won't be shown without the help of the jQuery on() method.

list.php - the data to be loaded in the listContainer div.

<table id='myTable'>
    <tr>
        <th>Name</th>
        <th>Action</th>
    </tr>
    <tr>
        <td>Mike Dalisay</td>
        <td>
            <div class='deleteAction'>Delete</div>
        </td>
    </tr>
    <tr>
        <td>Marykris De Leon</td>
        <td>
            <div class='deleteAction'>Delete</div>
        </td>
    </tr>
</table>

There are other previously used methods almost similar the jQuery on(), like live() and delegate(). But among those methods, jQuery on() is recommended to use (if you're using jQuery 1.7+). Users of older versions of jQuery should use delegate() in preference to live().

For FREE programming tutorials, click the red button below and subscribe! :)
Thanks for the comments!
 
 
Fundamentals
"First do it, then do it right, then do it better."
~ Addy Osmani
"Talk is cheap. Show me the code."
~ Linus Torvalds
Let's Stay Connected!
g+ r
Android app on Google Play
© 2011-2014 The Code Of A Ninja. All rights reserved. Proudly Powered by Google Blogger. Images, logos, marks or names mentioned herein are the property of their respective owners.