Two Example Usage of jQuery On() Method

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.

"Home

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:

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.

Loading Table List to a DIV

jquery-on-tutorial---load-table-list

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.

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().

If you want to read more about this topic,here are some links that can help.

Download Source Codes
You can download all the code used in this tutorial for only $9.99 $5.55!
[purchase_link id="12247" text="Download Now" style="button" color="green"]

Related Tutorials

We listed all our high quality full-stack web development tutorials here: Click here.

Hi! I'm Mike Dalisay, the co-founder of codeofaninja.com, a site that helps you build web applications with PHP and JavaScript. Need support? Comment below or contact [email protected]

I'm also passionate about technology and enjoy sharing my experience and learnings online. Connect with me on LinkedIn, Twitter, Facebook, and Instagram.