0

I appended the checkbox input field from javascript. after that, I need to catch click event of that checkbox field. But I could not. I tried with these following instruction:
- An append in jquery code and click function?
- jQuery 1.9 .live() is not a function.

This is my code

var htmlData='<input type="checkbox" name="is_pay[]" class="is_pay">';
$('.container').append(htmlData);

$('.is_pay').on('click', function(){
        alert('hi');
});
Jack Bashford
  • 38,499
  • 10
  • 36
  • 67

3 Answers3

2

Because that item does not exist when the script is run, so listen for a click on .container:

var htmlData='<input type="checkbox" name="is_pay[]" class="is_pay">';
$('.container').append(htmlData);

$(".container").on("click", ".is_pay", function() {
    alert("hi");
});
Jack Bashford
  • 38,499
  • 10
  • 36
  • 67
0

Event handler will only run if element exist on the page therefore your script click handler is not worked as you are adding checkbox dynamically .

If any new element injected to page dynamically then use delegated event to attach event handler . Replace click handler with the following code

$("document").on("click", ".is_pay", function() {
    alert("hi");
});
UnmeshD
  • 159
  • 2
  • 11
0

You can simply handle with .click()

var htmlData='<input type="checkbox" name="is_pay[]" class="is_pay">';
$('.container').append(htmlData);

$('.is_pay').click(function(event) {
   alert('hi');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='container'></div>
Parth Raval
  • 3,325
  • 2
  • 20
  • 30