mercredi 7 février 2018

AJAX/jQuery Generated Inputs not Recognized by Other jQuery Scripts

I have what I assume is a relatively simple issue. For testing purposes I have made it so simple so as to locate the issue.

I have a jQuery script that works alongside AJAX to return some results next to checkboxes, here it is below:

$.ajax({
            type:'GET',
            url: '/customers/details/emails',
            dataType:'json',
            data: {
                'customerID': $('select[name=payer_id]').val(),
               '_token': $('input[name=_token]').val(),
            },
                success: function(data) {
                    $('.errorTitle').addClass('hidden');
                    $('.errorContent').addClass('hidden');

                    if ((data.errors)) {
                        setTimeout(function () {
                            $('#createOrigin').modal('show');
                            toastr.error('Check your inputs!', 'Error Alert', {timeOut: 5000});
                        }, 500);

                        if (data.errors.title) {
                            $('.errorTitle').removeClass('hidden');
                            $('.errorTitle').text(data.errors.title);
                        }
                        if (data.errors.content) {
                            $('.errorContent').removeClass('hidden');
                            $('.errorContent').text(data.errors.content);
                        }
                    } else {
                         $.each(data, function(i,val) {
                                    $('<tr>').append(
                                    $('<td>').html('<input type="checkbox" id="emailCheckboxSelect">'),
                                    $('<td>').text(val)).appendTo('#customerEmails');

               });
              }
             }
            });

As you can see near the end, for each result a table row is appended, with a checkbox with an id of "emailCheckboxSelect".

Now to my problem, these are obviously dynamically created elements so I believe this is the issue with this script (a simple dummy just to locate the issue). Here is that script that should work:

$(function(){
    $('#emailCheckboxSelect').click(function(){
        alert('clicked');
    });
});

This doesn't work with the dynamically created elements. However, I did add " Checkbox" directly to my page, and this does set off the alert.

So what am I doing wrong and what do I need to do so that jQuery can recognize dynamically created elements? Thanks - Matt




Aucun commentaire:

Enregistrer un commentaire