0

I have this code in the bottom of the page:

$('.checkbox-class:checkbox').on('click', function () {
    alert($(this).val());
});

I have a datatable with a td with this input:

<input class="checkbox-class" type="checkbox" name="compartir[]" value="{{$row->id}}">

I can see the alert on each click of the checkbox of the first page, but when I move to the 2nd page, the script is not listening this clicks. But, if I reload the page, and move first to the 2nd page, then I do my first clicks, javascript can catch them well, but if I move to the 1st page, javascript doesn't listen them (on that, the 1st page)

I don't get it whay is happening this.

EDIT: A fiddle about it:

https://codepen.io/anon/pen/EBjNPW

1 Answer 1

1

You can use delegation for the event by attaching it to the table itself and only firing on the specific class type, I take it you are using JQuery as you have it in your example above, so this should serve your needs, notice how the 2nd parameter of .on is the className of the checkbox items in the table, this will then fire anytime a checkbox with that className inside the parent table is clicked:

$('#yourTable').on('click', '.checkbox-class:checkbox', function(){
    alert($(this).val());
});
Sign up to request clarification or add additional context in comments.

4 Comments

@pmirnd Glad to help. Have a good day. Also, this article explains what I used in my answer with more detail (learn.jquery.com/events/event-delegation)
Thanks. Can I do the same with each? I'm trying something like: $('#yourTable').each('click', '.checkbox-class:checkbox', function(){
@pmirnd I don't believe that works with .each, .each is for iterating a set of elements. But if I'm wrong on that, feel free to let me know. From what I see in the documentation here (api.jquery.com/jquery.each), that isn't valid code in your example.
Thanks mate. I've just asked it here: stackoverflow.com/questions/56570595/…

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.