Tim Aych
Tim Aych

Reputation: 1365

jQuery on a dynamically (PHP) created checkbox

I have a drop-down that's populated with database records along with a button for displaying each record's information via an AJAX call to a processing page. If the record's 'approval' database field is true, the check box is displayed as checked, if not, it's unchecked. Up to this point, everything works fine.

My problem is not being able to use a jQuery selector on the dynamically generated check box. When the checkbox is changed, nothing happens--no console logs or anything.

I haven't re-factored my code to avoid repetition/etc, so please excuse the sloppiness:

PHP (returned code through AJAX call):

if($approved) {
    echo '<p><strong>Approved: </strong>';
    echo '<input type="checkbox" id="checkbox_unapprove" checked>';
    echo '</p>';
} else {
    echo '<p><strong>Approved: </strong>';
    echo '<input type="checkbox" id="checkbox_approve">';
    echo '</p>';            
}

Portion of my jQuery:

$('#checkbox_approve').change(function(){
    console.log('clicked');
    var dropdown_id = $('#exchanges0 option:selected').attr('id');
    alert(dropdown_id);
});


$('#checkbox_unapprove').change(function(){
    console.log('clicked');
    var dropdown_id = $('#exchanges1 option:selected').attr('id');
    alert(dropdown_id);
});

I'm thinking that jQuery can't access #checkbox_approve or #checkbox_unapprove because they're not loaded into the DOM upon page load. Is this correct?

Upvotes: 1

Views: 265

Answers (2)

Bibear
Bibear

Reputation: 69

instead of binding your event in a $(document).ready() put it all on a standard function

function onDocumentLoad() {
$('#checkbox_approve').change(function(){
    console.log('clicked');
    var dropdown_id = $('#exchanges0 option:selected').attr('id');
    alert(dropdown_id);
});


$('#checkbox_unapprove').change(function(){
    console.log('clicked');
    var dropdown_id = $('#exchanges1 option:selected').attr('id');
    alert(dropdown_id);
});
}

SO you can call this function in the $(document).ready(); and also after your AJAX script has added content to the page. therefor you events will be properly binded to your new added elements

Upvotes: 0

Use .on()

As elements are added dynamically you can not bind events directly to them .So you have to use Event Delegation.

$(document).on('change','#checkbox_approve',function(){
    console.log('clicked');
    var dropdown_id = $('#exchanges0 option:selected').attr('id');
    alert(dropdown_id);
});

Syntax

$( elements ).on( events, selector, data, handler );

Upvotes: 2

Related Questions