0

I have created dynamic checkbox using jquery based on the data from a web service.

var checkbx = '<td><input type="checkbox" class="select_ticket" data-id="'+ newjsondata[i].id +'"/></td>'; tr.append(checkbx);

When I click on the checkboxes nothing happens, in other words the events do not respond.

function test() {
  console.log('okokok');
  var id = $(this).data("id");
  alert(id);
}
$( ".select_ticket" ).on( "click", test );

I event tried with click and change events without any success.

Can someone help me understand on where I have made a mistake.

4
  • You need to show more of your code. You definition of the checkbox needs to be defined before you can add an event to it. You are appending said checkbox to a row in what looks like html but you have the HTML in what looks like JS. A lot needed here before an answer can happen Commented Jun 15, 2017 at 20:05
  • 1
    You can add $( ".select_ticket" ).on( "click", test ); after tr.append, the problem is that you will register again the event for all items. You can do $( ".select_ticket" ).off("click") before to skip this problem and the register click again for all items. Anyways the answer given by Quagaar is the best and easier option Commented Jun 15, 2017 at 20:08
  • If the html renders fine without errors then it's the click handler requiring delegated event, as already answered by Quagaar. Commented Jun 15, 2017 at 20:14
  • Thank you all Quagaar's method helped me. Commented Jun 15, 2017 at 21:19

1 Answer 1

3

The click handlers are only registered for checkboxes that exist at the time of the registration. Change your handler registration like this to register also checkboxes that are newly added to the DOM:

$('body').on('click', '.select_ticket', test);

(You should exchange "body" for a more restrictive selector)

Sign up to request clarification or add additional context in comments.

3 Comments

I would recommend $(document).on('click', '.select_ticket', test);
@Woodrow Why document? Normally I tend to narrow down the selectors as far as possible. I don't really know how jQuery works here, but I would think that watching the whole document for changes is more costly than only watching a (more or less) small portion of the DOM.
I agree on narrowing down the selectors if you can, I just know document comes in handy if for some reason your click event is on something so dynamic that it is hard to narrow down which element to bind it on.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.