Jingjie Yang
Jingjie Yang

Reputation: 625

Jquery .on event not firing in chrome

I am trying to reproduce some thing that works on codecademy: https://www.codecademy.com/en/courses/web-beginner-en-v6phg/2/5?curriculum_id=50a3fad8c7a770b5fd0007a1

However, when I copied down the html, css, and js files and ran it with google chrome, nothing was working. I noticed the missing <script> link to Jquery and added it, and fixed the 'add' function; however the 'remove part' never worked.

Ps. I made sure the script is correctly linked by adding an alert, which fired.

Here is the html:

<!DOCTYPE html>
<html>
    <head>
        <title>To Do</title>
        <link rel="stylesheet" type="text/css" href="stylesheet.css"/>
        <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js?ver=1.4.2'></script>
        <script type="text/javascript" src="script.js"></script>
    </head>
    <body>
        <h2>Checklist</h2>
        <form name="checkListForm">
            <input type="text" name="checkListItem"/>
        </form>
        <div id="button">Add!</div>
        <br/>
        <div class="list"></div>
    </body>
</html>

and jquery (js) file:

$(document).ready(function() {
    $('#button').click(function() {
        var toAdd = $('input[name=checkListItem]').val();
        $('.list').append('<div class="item">' + toAdd + '</div>');
        $('input[name=checkListItem]').val('');
    });
    $(document.body).on('click', '.item', function(event) {
        $(this).remove();
    });
});

Upvotes: 0

Views: 235

Answers (2)

Farhan
Farhan

Reputation: 1483

If you sticky with old library then use .live() instead of .on(). Hope this will work for you.

$(document).ready(function() {
    $('#button').click(function() {
        var toAdd = $('input[name=checkListItem]').val();
        $('.list').append('<div class="item">' + toAdd + '</div>');
        $('input[name=checkListItem]').val('');
    });
    $(".item").live('click', function() {
        $(this).remove();
    });
});

Demo: https://jsfiddle.net/8s19ehh8/5/

Upvotes: 1

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

I just found out the issue to be using old version of jQuery. You are using 1.4.2, which doesn't have the .on() function.

<script type='text/javascript' 
        src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js?ver=1.4.2'></script>
<!-------------------------------------------------------^^^^^

Solution: Use the latest version of jQuery 1.x, which is 1.12.

From the manual:

manual

I would really suggest you to check the console first before posting something here.

Upvotes: 4

Related Questions