0

The contact_container div holds contact children, within these children is a checkbox. I use ajax to append these children to the container. Once I append the html and click a childs checkbox. The .click does not recognize the newly added checkboxes, Only the children work on page load. Below are working samples of my HTML and Jquery.

Can you offer a solution so that the appended checkboxes are picked up when they are clicked? Thanks

Here is my HTML markup:

   <div id="contact_container">
    <div class="contact">
        <div class="contact_checkbox">
             <div class="checkbox_container">
                 <div class="checkbox">
                     <input class="testing_checkbox" type="checkbox" name="contacts[]" value="bf6b0049059ec8998601f8fe20acb68ecafe2d44">
                </div>
             </div>
        </div>
        <div class="contact_info">
            <div class="contact_image">
                <img src="image.jpg" width="50" height="50" alt="Profile Picture">
            </div>
            <div class="contact_name"><span>Caroline Airey</span>
            </div>
       </div>
    </div>
</div>
<div id="x_message" class="inputdata" style="overflow: hidden; display: none;">
    <label>Message:</label>
    <span><textarea name="x_message" placeholder="Enter a message to send to your contact(s)"></textarea></span>
    <div class="clear"></div>
    <button class="form_button">Add Contact to Network</button>
</div>

Here is my Jquery:

$( ".checkbox" ).click(function() {
    var checked = $('.testing_checkbox:checked').length;
    $('#testing').val(checked);
    if (checked > 0){
        $('#x_message').show(1000);
    }
    else{
        $('#x_message').hide(1000);
    }
});
cwiggo
  • 2,541
  • 9
  • 44
  • 87
  • possible duplicate of [In jQuery, how to attach events to dynamic html elements?](http://stackoverflow.com/questions/1359018/in-jquery-how-to-attach-events-to-dynamic-html-elements) – xDaevax Aug 29 '14 at 12:48

2 Answers2

3

You will need the Parent reference to bind the element properly to jquery try this

$(parentObj).on("click",".checkbox",function() {
var checked = $('.testing_checkbox:checked').length;
$('#testing').val(checked);
if (checked > 0){
    $('#x_message').show(1000);
}
else{
    $('#x_message').hide(1000);
}
});

The parentObj is the div or the html element you've appended the html code with ajax call

thickGlass
  • 540
  • 1
  • 5
  • 19
  • Thanks, I will mark this as the answer due to the explanation of the parentObj, thats where I was going wrong! I was binding the parent div rather than the element i've appended the html code to. Reputation++ – cwiggo Aug 29 '14 at 12:54
0

Use this jQuery method instead:

$(".checkbox").on("click", function()
{
    // Your code here
});

This will grab clicks from elements that are dynamically added to your page after it initially loads :)

erlingormar
  • 451
  • 2
  • 11