1
        $(function() {

            $.getJSON("companies.json", function(response) {

                var html = '<table id="tbl">';
                response.businesses.forEach(function(row) {
                    html += '<tr><td><a href="#" class="move" idname="' + row.id + '">' + row.id + '</a></td><td>' + row.name;
                });
                html += '</table>';

                $("#tabledata").html(html);
            });


            $(".move").click(function() {

                var $id = $(this).attr("idname");

                $.getJSON("companies.json", function(response) {


                    $.map(response.businesses, function(obj) {
                        if (obj.id == $id)
                            console.log(obj);
                        return obj; // or return obj.name, whatever.
                    });
                });
            });
        });

HTML:

    <div id="tabledata" class='left'></div>
    <div class="right"></div>

Please help?

sanchez
  • 4,469
  • 3
  • 20
  • 51
vini
  • 4,198
  • 23
  • 72
  • 152

4 Answers4

2

If you use event delegation, your problem goes away (and your app becomes more performant and less prone to memory leaks).

// Only do this once, when your page loads...
$(document.body).on('click', '.move', function (ev) {
    // This is the link that was clicked.
    var $targ = $(ev.target);
});
Ryan Wheale
  • 18,754
  • 5
  • 58
  • 83
2

As your .move element is added to your page dynamically, you have to make use of jQuery's on() method to delegate the event to an ancestor of the .move element which does exist when your JavaScript first loads.

$(document).on('click', '.move', function() { ... });

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

You can read more about jQuery's event delegation here.

James Donnelly
  • 117,312
  • 30
  • 193
  • 198
0

Try This

$('#tabledata').on('click', '.move', function(e) { ... });
Muhammed Shuhaib
  • 314
  • 6
  • 18
0

The reason the event isn't being triggered is because the event is only added to elements that exist on the page when you call the .click() method.

Instead, you can use event delegation:

$(document.body).on('click', '.move', function (ev) {
    var $targ = $(ev.target);
}); 

which really says: call the function when any element that matches .move that's inside document.body is clicked.

I know others have said this already but I wanted to make event delegation clearer.

Ariel
  • 4,402
  • 2
  • 18
  • 23