0

I have following button on my view:

<td>    
<?php 
$data = array(
    'name' => $id,
    'class' => 'do_the_job',
    'content' => 'Do the job'
             );
echo form_button($data);
?>    
</td>

When I click on that button it does what I expected because I have the following function in my EXTERNAL JS file

$(document).ready(function() {
        $(".do_the_job").click(function() {
   //does the job
});
});

I have also another controller and view and I created the button (with same class) for it dynamically using jQuery:

table.html('<button name="'+id+'" class="do_the_job">Do the job</button>');

The problem is that when I click on that button, it does not work despite the fact that the button has the same class as the first button and it is expected to do the work as it is described in my EXTERNAL JS file.

I have researched and saw that I should use the function on() instead of click(). I have modified my external JS file in the following way but it still does not work:

$(".do_the_job").on("click", function() {      
   //does the job
});

Could you please help me to solve the problem?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
EducateYourself
  • 971
  • 2
  • 13
  • 32

2 Answers2

1

In your use case you want to use the on differently, you're still binding your event like using the click method(assuming add_to_trip is what you formerly referred to as do_the_job). What you want is:

$("#static_parent_element").on(
    "click",
    ".add_to_trip",
    function () {/*Do the job*/}
);

This checks propagating events from elements in the static container against the given matcher, allowing you to add and remove elements dynamically.

LJᛃ
  • 7,655
  • 2
  • 24
  • 35
1

This may be because of direct event listener.In your case you may consider delegated event listener.

For example if you have Html code

<!DOCTYPE html>
<html>
<body>

<button type="button" id="foo" class ="dothisjob" >Foo</button>
<button type="button" id="bar" class ="dothisjob" >Bar</button> 
</body>
</html>

and if your event listener written like this

$(".dothisjob").on("click", function() {...});

this will handle only click event of static classes which was aadded at page load.(direct event listener)

this click event listener won't work for if you add class='dothisjob' dynamically such as
addclass('dothisjob') toggleclass('dothisjob').

In order to handle event listeners for dynamically added classes you should use delegated event listeners .

To achieve that you should give the responsibility to some static elements of your page.(delegated event listener)

$("body").on("click", ".dothisjob", function() {...});

Now body is responsible to listen the events. If you add .dothisjob dynamically to one of the child elements of body this will work.

Useful SO answer Direct vs. Delegated - jQuery .on()

Community
  • 1
  • 1
ManirajSS
  • 2,295
  • 5
  • 26
  • 50